Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update README.md after commits bff756b and 7709f45 #259

Merged
merged 2 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,24 +32,41 @@ 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'
})

// 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',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-startRedirectPath: '/login/facebook',
+startRedirectPath: '/login/discord',

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 })