|
| 1 | +'use strict' |
| 2 | + |
| 3 | +// This example assumes the use of the npm package apple-signin in your code. |
| 4 | +// This library is not included with fastify-oauth2. If you wish to implement |
| 5 | +// the verification part of Apple's Sign In REST API yourself, |
| 6 | +// look at https://github.com/Techofficer/node-apple-signin to see how they did |
| 7 | +// it, or look at https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api |
| 8 | +// for more details on how to do it from scratch. |
| 9 | + |
| 10 | +const fastify = require('fastify')({ logger: { level: 'trace' } }) |
| 11 | +const appleSignin = require('apple-signin') |
| 12 | + |
| 13 | +const oauthPlugin = require('..') |
| 14 | + |
| 15 | +const CLIENT_ID = '<CLIENT_ID>' |
| 16 | + |
| 17 | +fastify.register(oauthPlugin, { |
| 18 | + name: 'appleOAuth2', |
| 19 | + credentials: { |
| 20 | + client: { |
| 21 | + id: CLIENT_ID, |
| 22 | + // See https://github.com/Techofficer/node-apple-signin/blob/master/source/index.js |
| 23 | + // for how to create the secret. |
| 24 | + secret: '<CLIENT_SECRET>' |
| 25 | + }, |
| 26 | + auth: oauthPlugin.APPLE_CONFIGURATION |
| 27 | + }, |
| 28 | + startRedirectPath: '/login/apple', |
| 29 | + callbackUri: 'http://localhost:3000/login/apple/callback' |
| 30 | +}) |
| 31 | + |
| 32 | +fastify.get('/login/apple/callback', function (request, reply) { |
| 33 | + this.appleOAuth2.getAccessTokenFromAuthorizationCodeFlow( |
| 34 | + request, |
| 35 | + (err, result) => { |
| 36 | + if (err) { |
| 37 | + reply.send(err) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + appleSignin.verifyIdToken( |
| 42 | + result.id_token, |
| 43 | + CLIENT_ID |
| 44 | + ) |
| 45 | + .then(payload => { |
| 46 | + // Find all the available fields (like email) in |
| 47 | + // https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/authenticating_users_with_sign_in_with_apple |
| 48 | + const userAppleId = payload.sub |
| 49 | + |
| 50 | + reply.send(userAppleId) |
| 51 | + }) |
| 52 | + .catch(err => { |
| 53 | + // Token is not verified |
| 54 | + reply.send(err) |
| 55 | + }) |
| 56 | + } |
| 57 | + ) |
| 58 | +}) |
| 59 | + |
| 60 | +fastify.listen(3000) |
0 commit comments