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;
};
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:
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.
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’