I'm getting `UnauthorizedError: jwt malformed at new UnauthorizedError` with `credentialsRequired: false`

I’m trying to implement an API endpoint where presence of a token is optional. If I understand this correctly, the way to do this is to add credentialsRequired: false as one of the params to the middleware.
However, requests made to this endpoint that do not have a token, result in UnauthorizedError: jwt malformed at new UnauthorizedError

So just to make sure it’s clear, it does not appear to be a problem with validating the tokens in itself, because if the token is present everything works as expected. But the error shows up without a token.

My checkJwt is configured as follows

const { expressjwt } = require("express-jwt");
const jwksRsa = require("jwks-rsa");
const domain = process.env.AUTH0_DOMAIN, audience = process.env.AUTH0_AUDIENCE;

const checkJwt = expressjwt({
	secret: jwksRsa.expressJwtSecret({
		cache: true,
		rateLimit: true,
		jwksRequestsPerMinute: 5,
		jwksUri: `https://${domain}/.well-known/jwks.json`
	}),
	credentialsRequired: false,
	audience: audience,
	issuer: `https://${domain}/`,
	algorithms: ["RS256"]
});

module.exports = {
	checkJwt
};

The route in express is as follows

router.post('/membership/upgrade', checkJwt, require('./handlers/membership').upgrade);

I have checked the request headers on the client side and it’s not adding Bearer.

Can anybody point out what I’m doing wrong?

Worked out what the issue is. Turns out it was sending the header, but I missed it because it was sending null instead of omitting the header completely

This issue is pretty straightforward: In most circumstances, it’s logically disjointed to allow the forward sequence of a request without credentials, yet deny a request that has expired credentials.

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