Search code examples
node.jsmiddlewareauth0

Auth0 Node api middleware how message to non-valid users


I have an end-point in my Node app which I want to be accessible both from logged in and not logged in users. for not logged in i want to show less data. on Auth0 example the message(page) will only be shown when user is logged in while if user isn't logged in just an not auth error returns.

How can I still display something except the not auth error?

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

// Authentication 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_AUTH0_DOMAIN/.well-known/jwks.json`
  }),

  // Validate the audience and the issuer.
  audience: '{YOUR_API_IDENTIFIER}',
  issuer: `https://YOUR_AUTH0_DOMAIN/`,
  algorithms: ['RS256']
});
app.get('/api/private', checkJwt, function(req, res) {
  res.json({
    message: 'Hello from a private endpoint! You need to be authenticated to see this.'
  });

});


Solution

  • You can do this using credentialsRequired: false parameter.

    One example:

    const verifyJwtMiddleware = jwt({
      secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `${process.env.AUTH0_ISSUER}.well-known/jwks.json`,
      }),
      credentialsRequired: false,
      audience: process.env.AUTH0_AUDIENCE,
      issuer: process.env.AUTH0_ISSUER,
      algorithms: ['RS256'],
    });
    
    app.get('/api/user-details', verifyJwtMiddleware, (req, res) => {
      const data = { authenticated: false };
      if (req.user) {
        data.authenticated = true;
      }
    
      res.send(data);
    });