Skip to Content

Authentication and Authorization with OAuth 2.0 and OpenID Connect: Part 2 – Securing the Backend

June 7, 2022 by
Chris Kingdon
| No comments yet


In Part 1 of my series on authentication and authorization, I went over how to create a secure basic front-end application behind a login screen. In today’s post, we’ll take it a step further and introduce a backend component. Since backends to applications are often stateless, the process to allow access is somewhat different and relies on something called an access token. These access tokens given to us by our auth server will allow us to prove our identity to a backend server and hit secured routes. So let’s jump into it!

Step 0: Initial Setup

Before we begin, be sure to either follow the steps in my Part 1 blog post or just grab the final result from my Github here. Now that we have the frontend we need to create our backend. If you haven’t already, clone my Github repo for this project and open the following folder: HowTo -> Auth -> OAuth2_OpenIDConnect -> Part 2 -> StarterAppBackend. Run npm install and then npm run dev to start the app. The starter app is made up of two routes. The first route is /health. This route will be an anonymous route (anyone can call it with or without authentication) and the second route /secure-route will be a protected route that just returns some text. Finally, any route besides those two will return 404 not found.

To test this out you will need a tool to call the API. I will use Postman for this demo. Open Postman and in the URL enter http://localhost:3000/health and click send. We should get the text “Healthy” back.

Hitting the Health Route
Hitting the Health Route

Similarly, we can call the starter app’s secure route before adding authentication:

Calling the Secure Route Before Adding Authentication
Calling the Secure Route Before Adding Authentication

We can see that both starter routes are currently public. Let’s fix that!

Step 1: Auth Middleware

Before we begin I should mention that what I’m about to show should NEVER be done from scratch in a production scenario. Always use a prebuilt library (for example jsonwebtoken) to validate your tokens. What I am showing here is for you to learn the end-to-end process of how OIDC and OAuth 2.0 work. This is by no means a complete solution. With that disclaimer out of the way, let’s begin.

Start by installing the axios package: npm install axios. Now create a new file under src called authMiddleware.js with the following contents:

export default (req, res, next) => {
  return next()
}

Now in routes.js import the new module and then update the secure route to use it:

import authMiddleware from './authMiddleware.js'
router.get('/secure-route', authMiddleware, (req, res) => {
  res.send('Super secret stuff')
})

This tells the route to call our middleware function before continuing which will allow us to do our authentication. Right now our middleware just passes on without checking anything so nothing should change just yet. The first thing we should check in our auth middleware is to see if the header of the request contains a token or not. Back in our middleware change the function to include the following code:

export default (req, res, next) => {
  const authHeader = req.headers.authorization
  const token = authHeader && authHeader.includes('Bearer ') ? authHeader.split('Bearer ')[1] : null

  if (!token) {
    return res.status(401).send('Unauthorized');
  }

  // Do not call next() until the signature and claims have been verified.
  return res.status(401).send('Unauthorized')
}

Requests with no bearer token now receive a 401. The presence of a bearer token does not establish identity. Keep the route closed until the signature and claims checks below succeed. Postman’s Authorization tab is where the client’s authentication is configured.

Postman Authorization Tab (example token and response omitted)
Postman Authorization Tab (example token and response omitted)

Once we’ve extracted a token, the next step is to check its format before trying to verify it. A JWT token is made up of 3 parts: The header, the body, and the signature. So let’s verify that all 3 parts are there:

const tokenParts = token.split('.')

if (tokenParts.length !== 3 || tokenParts.some(part => !part)) {
  console.warn('Invalid token.')
  return res.status(401).send('Unauthorized')
}

Each part is base64url-encoded. Decode the header and body as JSON, but keep the signature as bytes for verification:

try {
  const tokenHeader = JSON.parse(Buffer.from(tokenParts[0], 'base64url').toString('utf8'))
  const tokenBody = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString('utf8'))
  const tokenSignature = Buffer.from(tokenParts[2], 'base64url')

  // Add signature and claim checks here before continuing.
} catch {
  console.warn('Invalid token.')
  return res.status(401).send('Unauthorized')
}

Here’s what the decoded pieces look like with illustrative values. Don’t print live tokens to logs:

Header: { alg: 'RS256', typ: 'JWT', kid: 'example-key-id' }
Body: { sub: 'example-user', name: 'Example User', iat: 1516239022 }
Signature: <signature bytes>

The header contains information about the JWT such as what algorithm was used to sign it and the key ID. The body contains the actual data like the subject, aka who this token is about, and iat, aka when this token was issued. The signature is what we need to validate to prove that the token has not been tampered with. If we can’t validate the signature then the rest of the token can’t be trusted.

Step 3: Setup Postman to Get a Valid Token

Before we write the code to verify the signature let’s update Postman so that we can get a real token from our auth provider. First, create an API in Auth0 that we will use for our audience. Navigate to Applications -> APIs and click Create API. Give it any name, an identifier (you will use the identifier as the audience for the next part), and select RS256 as the signing algorithm.

Creating an API in Auth0
Creating an API in Auth0

Now, in Postman go back to the Authorization tab and change the type to OAuth 2.0. Fill out the following settings:

  • Token Name – Whatever you want (I used DemoToken)
  • Grant Type – Authorization Code (With PKCE)
  • Authorize using browser – Leave unchecked for this example
  • Auth URL – This is the /authorize URL for your auth server. (If you recall from Part 1 you can get this from the .wellknown endpoint). For Auth0 it will be something like https://<your-tenant-name>.us.auth0.com/authorize?audience=<your-audience>
  • Access Token URL – You can get it from the well-known endpoint or build it based on this: https://<your-tenant-name>.us.auth0.com/oauth/token
  • Client ID – The client ID of the application you used to authenticate in Part 1.
  • Code Challenge Method – SHA-256
  • Scope – openid profile email
  • State – Use a fresh, unpredictable value for each authorization request and verify it on return.
  • Client Authentication – Send as Basic Auth header (the setting shown in this example; never put a client secret in a public browser application).
Postman OAuth 2.0 Settings
Postman OAuth 2.0 Settings

All of these settings should look at least somewhat familiar to you. This is because Postman is going to go through the same login flow that we built from scratch in Part 1. Go ahead and click “Get New Access Token” and sign in and then click “Use Token”. This will set the token we got back as the token to use for requests.

Step 4: Validate Token Signature

Now that we can get a legitimate token we need to verify the token signature. This is probably the most important part of token verification. If the signature can’t be verified then the token could be modified and cannot be trusted. Depending on how the token was issued there are a couple of ways we can verify the signature. For example, if it was our backend that issued the token using a symmetric algorithm, we would have a secret that we can use to verify the token signature. In our case, however, we’re using RS256 and need the provider’s public signing key. To begin we need to get the OpenID config so that we can find the key information.

Start by installing axios: npm install axios. Next, create a new file called config.js:

export default {
  domain: '<your-domain>.us.auth0.com'
}

Now we import it into our authMiddleware.js and use it to get the OpenID configuration (also change the function to be async):

import config from './config.js'
import axios from 'axios'

let openidConfig

export default async (req, res, next) => {
...

Now inside of our try-catch block:

const tokenHeader = JSON.parse(Buffer.from(tokenParts[0], 'base64url').toString('utf8'))
const tokenBody = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString('utf8'))
const tokenSignature = Buffer.from(tokenParts[2], 'base64url')

if (!openidConfig) {
  const configResponse = await axios.get(`https://${config.domain}/.well-known/openid-configuration`)
  openidConfig = configResponse.data
}

Once we have our OpenID config we can find the route which contains the key information:

const keyInfoResponse = await axios.get(openidConfig.jwks_uri)
const keyInfo = keyInfoResponse.data

Now that we have the key information we can use it to verify the token. We start by looking up the key that was used to sign the token. We look up the key by a field on the token called the “kid” aka the key ID. This field lives in the token header and should match one of the keys in the key info that we just got back:

if (tokenHeader.alg !== 'RS256' || typeof tokenHeader.kid !== 'string' || !tokenHeader.kid) {
  return res.status(401).send('Unauthorized')
}
const signingKey = keyInfo.keys.find(k => k.kid === tokenHeader.kid && k.kty === 'RSA')
if (!signingKey) {
  console.warn('Key not found.')
  return res.status(401).send('Unauthorized')
}

We now have all the info we need to verify the signature of our token. We could go through the process of building the public key in PEM format from scratch but to make things a bit easier we’ll install another library: npm install rsa-pem-from-mod-exp. If you would like to see the specifics of what it’s doing you can check out its GitHub here. Import it at the top of our middleware and then we’ll use it to get the public key and then use that to verify our token:

import getPem from 'rsa-pem-from-mod-exp'
import crypto from 'crypto'
const publicKey = getPem(signingKey.n, signingKey.e)

const verifier = crypto.createVerify('RSA-SHA256')
verifier.update(`${tokenParts[0]}.${tokenParts[1]}`)
const isValid = verifier.verify(publicKey, tokenSignature)

if (!isValid) {
  console.warn('Signature validation failed.')
  return res.status(401).send('Unauthorized')
}

Note: As mentioned earlier this is NOT a complete solution. The above code only illustrates RS256 validation. For production, use a maintained token verification library with an explicit algorithm, issuer, and audience. I have included an example in my GitHub.

Step 4: Validate the Token Claims

Once the signature is verified, the last step is to verify that a couple of the claims match what we expect and then pass the claims on to the rest of the API so that it can get info about the user. You could verify lots of different token claims but for the purposes of the demo we’ll verify the following claims:

  • iss – Issuer aka who created the token
  • aud – Audience aka who is the token intended for
  • exp – Expiration aka when does the token expire

Verifying the expiration:

const currentTime = Date.now() / 1000
if (!Number.isFinite(tokenBody.exp) || currentTime >= tokenBody.exp) {
  console.warn('Token is expired or has no valid expiration.')
  return res.status(401).send('Unauthorized')
}

Verifying the issuer and audience (don’t forget to update config.js):

const audiences = Array.isArray(tokenBody.aud) ? tokenBody.aud : [tokenBody.aud]
if (!config.audience || !audiences.includes(config.audience)) {
  console.warn('Invalid audience.')
  return res.status(401).send('Unauthorized')
}

if (!config.issuer || config.issuer !== tokenBody.iss) {
  console.warn('Invalid issuer.')
  return res.status(401).send('Unauthorized')
}

Last but not least, after the signature and claims checks succeed, set the request user to the token body so that we have access to it later on in the API pipeline:

req.user = tokenBody
return next()

And that’s it for the demo! The protected route now depends on a verified token.

Final Thoughts

Today we went over how to set up a backend API that has routes that require an authenticated user. The important part here is that once we verify the signature and relevant claims of a token we can use the verified claims to know things about the user. For example, a token could include a user’s roles which we could use in a route to determine what they are allowed to do in some route. In order to prove that the user has those roles we first have to verify that the token is legitimate. This is the authentication process. In our final part of this series, I’ll go over combining the UI and the API together as well as looking at some additional claims to create an admin-specific route. As always if you have any questions or comments let me know in the comments. I hope this was helpful!

Further Read & Resources:

Sign in to leave a comment
Authentication and Authorization with OAuth 2.0 and OpenID Connect: Part 3 – Bringing it all Together