OAuth - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki
Assume there are two servers, A and B, and an authorization server. Server A is hosting the REST API, and Server B would like to access the API.
- Server B sends a secret key to the authorization server to prove who they are and asks for a temporary token.
- Server B then consumes the REST API as usual but sends the token along with the request.
- Server A asks the authorization server for some metadata that can be used to verify tokens.
- Server A verifies the Server B’s request.
- If it’s valid, a successful response is sent and Server B is happy.
- If the token is invalid, an error message is sent instead, and no sensitive information is leaked.
Create an Authorization Server
Create Middleware to Verify Tokens in Express
const OktaJwtVerifier = require('@okta/jwt-verifier')
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: process.env.ISSUER,
clientId: process.env.CLIENT_ID
})
module.exports = async (req, res, next) => {
try {
const { authorization } = req.headers
if (!authorization) throw new Error('You must send an Authorization header')
`const [authType, token] = authorization.trim().split(' ')`
`if (authType !== 'Bearer') throw new Error('Expected a Bearer token')`
`const { claims } = await oktaJwtVerifier.verifyAccessToken(token)`
`if (!claims.scp.includes(process.env.SCOPE)) {`
`throw new Error('Could not verify the proper scope')`
`}`
`next()`
} catch (error) {
next(error.message)
}
}
Create a Test Client in Node
const token = btoa(${CLIENT_ID}:${CLIENT_SECRET})
const auth = await request({
uri: ${ISSUER}/v1/token,
json: true,
method: 'POST',
headers: {
authorization: Basic ${token}``
},
`form: {`
`grant_type: 'client_credentials',`
`scope: SCOPE`
`}`
`})`