Reading Auth0 Session Cookie in Express

Hello, Auth0 forums -

I’m wondering if it is possible to read / unsign an Auth0 session cookie in an Node / Express application. I am generating this cookie via a Next.js application using the nextjs-auth0 module and am able to read it in the app using the built in getSession method provided by the library.

The problem, however, is that I am now wanting to call an external API that I have built in Express and am having a hard time reading the a0:session cookie. Of course I have the session cookie secret that I am initializing the Next library with, however, I can’t seem to piece together how to unsign the cookie when utilizing the same secret.

Is there a library that I can use to be able to read an existing Auth0 session cookie? If not, is there any way to validate a user through the cookie in Express?

For clarification, I am not trying to store sessions in an express app. I am trying to authenticate a user based on the session cookie sent in a request from a client.

Thanks.

  • Which SDK this is regarding: nextjs-auth0
  • SDK Version: e.g. 0.16.1
  • Platform Version: e.g. Node 14.16.1

Hi @wkersting,

Welcome to the Community!

Instead of using the session cookie as proof for your external API that the user has logged in, you can instead use the Access Token. To get the Access Token, you can use the getAccessToken method:

import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(async function shows(req, res) {
  try {
    const { accessToken } = await getAccessToken(req, res, {
      scopes: ['read:shows']
    });
    const apiPort = process.env.API_PORT || 3001;
    const response = await fetch(`http://localhost:${apiPort}/api/shows`, {
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    });
    const shows = await response.json();

    res.status(200).json(shows);
  } catch (error) {
    res.status(error.status || 500).json({ error: error.message });
  }
});

When you specify an audience in your Next.js code using the API identifier of your registered API, then Auth0 will generate a JWT as the Access Token which your API can decode as shown in the Node.js/Express API quickstart example:

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwtAuthz = require('express-jwt-authz');
const jwksRsa = require('jwks-rsa');

// Authorization middleware. When used, the
// Access Token must exist and be verified against
// the Auth0 JSON Web Key Set
const checkJwt = jwt({
  // Dynamically provide a signing key
  // based on the kid in the header and 
  // the signing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://YOUR_DOMAIN/.well-known/jwks.json`
  }),

  // Validate the audience and the issuer.
  audience: 'YOUR_API_IDENTIFIER',
  issuer: [`https://YOUR_DOMAIN/`],
  algorithms: ['RS256']
});
1 Like

Hi Stephanie, thanks for your very swift response!

We just figured out how to read the signed session cookie moments ago. This solution is very helpful, however, I should have mentioned that the reason why we are attempting to read the cookie in an external service is to bypass having to use Next.js’s built in API routing. We are able to keep and read the cookies because the express microservices that we are creating will be hosted on the same domain under another version of our API.

Again thank you for your quick response!

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.