Skip to content

Commit

Permalink
Update README.md after commits bff756b and 7709f45 (#259)
Browse files Browse the repository at this point in the history
* Update README.md after commits bff756b and 7709f45

* Lint code
  • Loading branch information
giovanniruzzi committed May 3, 2024
1 parent 6e6cbfe commit 39378c8
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 4 deletions.
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ npm i @fastify/oauth2

## Usage

Two separate endpoints need to be created when using the fastify-oauth2 module, one for the callback from the OAuth2 service provider (such as Facebook or Discord) and another for initializing the OAuth2 login flow.

```js
const fastify = require('fastify')({ logger: { level: 'trace' } })
const oauthPlugin = require('@fastify/oauth2')
Expand All @@ -30,26 +32,43 @@ fastify.register(oauthPlugin, {
},
auth: oauthPlugin.FACEBOOK_CONFIGURATION
},
// register a fastify url to start the redirect flow
// register a fastify url to start the redirect flow to the service provider's OAuth2 login
startRedirectPath: '/login/facebook',
// facebook redirect here after the user login
// service provider redirects here after user login
callbackUri: 'http://localhost:3000/login/facebook/callback'
// You can also define callbackUri as a function that takes a FastifyRequest and returns a string
// callbackUri: req => `${req.protocol}://${req.hostname}/login/facebook/callback`,
})

// This is the new endpoint that initializes the OAuth2 login flow
fastify.get('/login/facebook', {}, (req, reply) => {
fastify.facebookOAuth2.generateAuthorizationUri(
req,
reply,
(err, authorizationEndpoint) => {
if (err) console.error(err)
reply.redirect(authorizationEndpoint)
}
);
});

// The service provider redirect the user here after successful login
fastify.get('/login/facebook/callback', async function (request, reply) {
const { token } = await this.facebookOAuth2.getAccessTokenFromAuthorizationCodeFlow(request)

console.log(token.access_token)

// if later you need to refresh the token you can use
// if later need to refresh the token this can be used
// const { token: newToken } = await this.getNewAccessTokenUsingRefreshToken(token)

reply.send({ access_token: token.access_token })
})
```

In short, it is necessary to initially navigate to the `/login/facebook` endpoint manually in a web browser. This will redirect to the OAuth2 service provider's login screen. From there, the service provider will automatically redirect back to the `/login/facebook/callback` endpoint where the access token can be retrieved and used. The `CLIENT_ID` and `CLIENT_SECRET` need to be replaced with the ones provided by the service provider.

A complete example is provided at [fastify-discord-oauth2-example](https://github.com/fastify/fastify-oauth2/blob/master/examples/discord.js)

### Usage with `@fastify/cookie`

Since v7.2.0, `@fastify/oauth2` requires the use of cookies to securely implement the OAuth2 exchange. Therefore, if you need `@fastify/cookie` yourself,
Expand Down
40 changes: 40 additions & 0 deletions examples/discord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict'

const fastify = require('fastify')({ logger: { level: 'trace' } })
const oauthPlugin = require('..')

fastify.register(oauthPlugin, {
name: 'discordOAuth2',
credentials: {
client: {
id: '<CLIENT_ID>',
secret: '<CLIENT_SECRET>'
},
auth: oauthPlugin.DISCORD_CONFIGURATION
},
startRedirectPath: '/login/facebook',
callbackUri: 'http://localhost:3000/login/discord/callback'
})

fastify.get('/login/discord/callback', async function (request, reply) {
try {
const token =
await this.discordOAuth2.getAccessTokenFromAuthorizationCodeFlow(request)
return reply.send(token)
} catch (error) {
return reply.send(error)
}
})

fastify.get('/login/discord', {}, (req, reply) => {
fastify.discordOAuth2.generateAuthorizationUri(
req,
reply,
(err, authorizationEndpoint) => {
if (err) console.error(err)
reply.redirect(authorizationEndpoint)
}
)
})

fastify.listen({ port: 3000 })

0 comments on commit 39378c8

Please sign in to comment.