0

I have a NextJS app which is using the quickstart guide to set up auth 0.

I have the following env vars

AUTH0_SECRET=123
AUTH0_BASE_URL=http://localhost:3000
AUTH0_ISSUER_BASE_URL='https://dev-1234.us.auth0.com'
AUTH0_CLIENT_ID=12345
AUTH0_CLIENT_SECRET=123456
AUTH0_AUDIENCE=
AUTH0_SCOPE='openid profile'

In my nextjs API route I am getting the token and sending it to a .NET rest api.

export default withApiAuthRequired(async function users(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const { accessToken } = await getAccessToken(req, res);
    const { path } = req.query;
    const response = await axios.get(`https://localhost:7230/Reports/${path}`, {
      headers: { Authorization: `Bearer ${accessToken}` },
      httpsAgent: new https.Agent({
        rejectUnauthorized: false,
      }),
    });

    res.status(200).json(response.data);
  } catch (error: any) {
    console.error(error);
    res.status(error.status || 500).end(error.message);
  }
});

In my rest API I am trying to validate the token and get the auth0 id. Here is the code.

 public async Task<string?> GetUserIdFromToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123")),
                ValidateIssuer = true,
                ValidIssuer = $"https://{"dev-1234.us.auth0.com"}/",
                ClockSkew = TimeSpan.Zero
            };

            try
            {
                var claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
                var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
                return userIdClaim?.Value;
            }
            catch(Exception ex) 
            {
                return null;
            }
        }

I have tried many variants of the code below above but nothing seems to work. Right now I am getting

{"IDX10609: Decryption failed. No Keys tried: token: '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'."}

but I am also getting lots of other types of errors if I try alternatives. Can anyone spot what I am doing wrong?

Ben
  • 116
  • 3
  • 14
  • I don't know what the `AUTH0_SECRET` is used for, but it's certainly not the public key that you would need to verify a RS512 signature. RS512 is an asymmetric signature algorithm and needs for verification the RSA public key that matches with the RSA private key that was used to sign the token. Therefore `IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("123"))` is certainly wrong. See where you can get the public key from and then, depending on the form in which it comes, load it. – jps Feb 22 '23 at 12:58
  • This is a link to the sample I was following: https://github.com/auth0-samples/auth0-nextjs-samples/tree/main/Sample-01. Another issue not sure if this is the problem but when I paste the key returned by getAccessToken into jwt.io it says invalid signature. But based off this info do you know where I can get the public key? – Ben Feb 22 '23 at 13:08
  • Sorry, can't go deeper into this now. Regarding jwt.io: As long as you don't not provide the correct (public) key, the token can't be verified. That's the same problem as in your code. – jps Feb 22 '23 at 13:24
  • No problem, I read somewhere if I go to auth0domain/pem it generates me a file. I did this and got a certificate. Is this what I put in IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(this value here)) ? Tried this and didn't work. And no worries if you cant go deeper hopefully someone else can see this and offer some advice :) – Ben Feb 22 '23 at 13:35
  • A certificate sounds good. But it's not a SymmetricSecurityKey. See [this Q/A](https://stackoverflow.com/questions/46294373/net-core-issuersigningkey-from-file-for-jwt-bearer-authentication) for an example about loading a cert. – jps Feb 22 '23 at 13:42
  • So I need to save the certificate to a file and reference the file? Surely what I am trying to do isn't that complicated and its documented somewhere? – Ben Feb 22 '23 at 14:03

1 Answers1

0

Is there a reason you're omitting the AUDIENCE in your env vars? This will result in an opaque token which may be causing you issues validating/extracting claims.

tyf
  • 1
  • Okay sounds good think we might be getting somewhere, do I need to amend the C# code for this? And should the audience be from the API application in auth0? – Ben Feb 26 '23 at 16:03
  • Yes exactly! It's the API identifier for the API you defined in the Auth0 dashboard - You'll need to pass the audience value wherever you are passing other params like "scope", etc. I'm not positive of the SDK you're using but see `withAudience` method [here](https://auth0.github.io/auth0.net/api/Auth0.AuthenticationApi.Builders.AuthorizationUrlBuilder.html#Auth0_AuthenticationApi_Builders_AuthorizationUrlBuilder_WithAudience_System_String_) for example. – tyf Feb 27 '23 at 22:02