Decoding JWT token on app route using express-jwt with RS256 encryption throws UnAuthorized Error

Issue

I am using Keycloak for authentication and using it’s middleware I have attatch a token to my request. I a trying to write an api route that retrieves user data using that token however, I get the following error:

UnauthorizedError: error:0909006C:PEM routines:get_name:no start line

Currently I am accessing the user data on the ‘/protected/’ route

app.get('/protected', jwt({
  secret: Buffer.from(process.env.TOKEN_SECRET as string), 
  algorithms: ['RS256'],
  requestProperty: 'auth',
  getToken: (req: any) => {
    const token = req?.kauth?.grant?.access_token;
    if (token) {
      console.log(token.token.toString())
      return token.token.toString();
    } 
    return null;
  }
}), (req: any, res: any) => {
  return res.json(req.auth)
});

I am getting my public key from keycloak console – but I still get that error.

** EDIT **

After adding the first and last line to the secret:

`-----BEGIN PUBLIC KEY-----\r\n${Buffer.from(process.env.TOKEN_SECRET as string)}\r\n-----END PUBLIC KEY-----`

I am now getting a new error:

UnauthorizedError: No authorization token was found

Solution

Keycloak doesn’t return the first and last lines basically the header and footer. So you need to add it yourself.

const publicKey = `-----BEGIN PUBLIC KEY-----\r\n${public_key}\r\n-----END PUBLIC KEY-----`

and use this in the express-jwt

Answered By – Aritra Chakraborty

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published