Azure Static Web App JWT token generation

I’ve got an Azure static web app (with Azure functions as API). When the user log’s in we generate a token with the following code:

function generateToken(user: User): string{
  const secretKey = process.env.SECRET_KEY;

  const tokenData = {
    userId: user.id,
  }

  const tokenOptions = {
    expireIn: "2 days"
  }

  const token = jwt.sign(tokenData, process.env.SECRET_KEY, tokenOptions});
  return token;
}

However, after calling a different function, the jwt.verify throws an invalid signature error.

try{
      const token = req.headers.authorization?.split(' ')[1];
      jwt.verify(token, process.env.SECRET_KEY, {algorithms: ['HS256']});
    }catch(tokenError){
      context.res = {
        status: 401,
        body: `tokenError: ${tokenError}\n
        token: ${req.headers.authorization?.split(' ')[1]}\n
        decode: ${JSON.stringify(jwt.decode(req.headers.authorization?.split(' ')[1]))}\n
        `
      };
      return;
    }

The code works perfectly locally, but after deploying it the payload changes from:

{"userId":2,"iat":1701863111,"exp":1702035911}

to

{"nbf":1701863176,"exp":1701863476,"iat":1701863176,"iss":"https://5de6fdb8-19cf-4d6e-9fd0-50a67c40ca59.scm.azurewebsites.net","aud":"https://5de6fdb8-19cf-4d6e-9fd0-50a67c40ca59.azurewebsites.net/azurefunctions"}

Any idea why? Thanks in advance!

I’ve tried several settings change for the generateToken, also checked that the enviroment variable is accessed by azure function.

Leave a Comment