Next.js invalid token using middleware, which token to use?

I’m using the code below to add an auth header to a backend .net core api. On the .net core side I’m getting an unauthorized 401 error using the accessToken. If I change it to IdToken from the getProfile call I get invalid audience. Which token should I use and how to track down why the auth check is failing?

export async function middleware(req: NextRequest) {
 
  const res = NextResponse.next();
  const user = await getSession(req, res);

  if (user) {
    if (user.accessTokenExpiresAt && user.accessTokenExpiresAt * 1000 < Date.now()) {
      return NextResponse.redirect('/api/auth/login')
    } 
    const requestHeaders = new Headers(req.headers);
    requestHeaders.set('Authorization', `Bearer ${user.accessToken}`);
    const response = NextResponse.next({ request: { headers: requestHeaders } });
    return response;
  }
  else{
    return NextResponse.redirect('/api/auth/login')
  }

  console.log(res.headers);
  return res;
};

Hey there @claim727 !

You should be using the access token against your backend API - Can you confirm the audience of the access token matches that of the API identifier of your API as defined in your Auth0 dashboard? Is your API middleware checking for scopes or anything else or just verifying the access token? A missing audience is a misstep here:

Let us know if this is not the case!

Hi tyf,

Appreciate the help! So the setup is as follows. I have a next.js front end and a .net core backend. The next.js setup was done following the auth0 next.js guide, and there’s no mention of setting up an audience config in that guide.

  1. Can confirm on the .net backend the audience matches the one on the dashboard. -.net config screenshot 2023-06-13_13-05-34.png -dashboard screenshot 2023-06-13_13-07-52.png
  2. No checking of scopes, just checking access token.

One thing to note is if I paste the user.accessToken into this site https://jwt.io/, I get an invalid token error 2023-06-13_13-10-26.png

If I paste the user.IdToken it checks out valid… so why would that be? Here’s an example of the access token ‘eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwiaXNzIjoiaHR0cHM6Ly9kZXYtc3c2MmxnNGE1cHVnc3ZtZy51cy5hdXRoMC5jb20vIn0…ypBsUKEiPtLuMm0E.bUvttx6EtALPkGWwMeuWupSFRUC2j8kgDbcrVD5GL7sfqtKLK-Q71lnt-Enw1lw2-rkV4uLVJzgqmsXjjWFvTA8boItW7VzM9mvboawkKirq2zEmQNz_wPbHeysp0_uMR12iCHs7FFoDYykWmjCO_iMO3DWqNwq4q_AD2iqcvfQQDBSx0ymw-PVUcnBFuAeDzV5-yJ_qS8knyfwo3IS6ufEYuEfhrX8jEpbplLMlsAspnNWL9CMNnZcsCxEpEzNXXqklwvHGnuredRSirsUJX4ty22IFhC8296nWLkXzGv66kMDt0ttRICQFqvX7TtVWDM9xSPDupAdLuLdxF23_yYt4ulQaVJc.-EEbiuZhXK6PPEWlok7DyA’