forked from fastify/fastify-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-with-pkce.js
84 lines (75 loc) · 2.19 KB
/
google-with-pkce.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict'
const fastify = require('fastify')({ logger: { level: 'trace' } })
const sget = require('simple-get')
const cookieOpts = {
// domain: 'localhost',
path: '/',
secure: true,
sameSite: 'lax',
httpOnly: true
}
// const oauthPlugin = require('fastify-oauth2')
fastify.register(require('@fastify/cookie'), {
secret: ['my-secret'],
parseOptions: cookieOpts
})
const oauthPlugin = require('..')
fastify.register(oauthPlugin, {
name: 'googleOAuth2',
scope: ['openid', 'profile', 'email'],
credentials: {
client: {
id: process.env.CLIENT_ID,
secret: process.env.CLIENT_SECRET
},
auth: oauthPlugin.GOOGLE_CONFIGURATION
},
startRedirectPath: '/login/google',
callbackUri: 'https://localhost:3000/interaction/callback/google',
cookie: cookieOpts,
pkce: 'S256'
/* use S256:
Most modern providers (authorization servers) that are up to date with standards,
will support S256 and also announce that in discovery endpoint (.well-known/openid-configuration):
...
"code_challenge_methods_supported": [
"S256",
"plain"
]
...
"plain" is also supported in this library but it's use is discouraged.
Only do it in case that you use some legacy provider (authorization server),
and you see provider's .well-known/openid-configuration
endpoint has only that single challenge method:
...
"code_challenge_methods_supported": [
"plain"
]
*/
})
fastify.get('/interaction/callback/google', function (request, reply) {
// Note that in this example a "reply" is also passed, it's so that code verifier cookie can be cleaned before
// token is requested from token endpoint
this.googleOAuth2.getAccessTokenFromAuthorizationCodeFlow(request, reply, (err, result) => {
if (err) {
reply.send(err)
return
}
sget.concat({
url: 'https://www.googleapis.com/oauth2/v2/userinfo',
method: 'GET',
headers: {
Authorization: 'Bearer ' + result.token.access_token
},
json: true
}, function (err, res, data) {
if (err) {
reply.send(err)
return
}
reply.send(data)
})
})
})
fastify.listen({ port: 3000 })
fastify.log.info('go to https://localhost:3000/login/google')