Resolved: How to retrieve a JWT access token from Azure B2C using `NextAuth.js`

Question:

my infrastructure is as follows:
  • I have a back-end Web API that uses Azure B2C authentication (respectively via JWT tokens)
  • I have a front-end app written on Next.js and it uses NextAuth.js to manage the authentication.

Everything seems ok – I can authenticate users in the front-end with the registered identity providers but… I need to call the back-end with an access token from Azure B2C so my requests are authenticated.
What is the correct way of managing this access token? I could not find any information about whether or not I should generate it by myself or there is some mechanism to simplify all this?
There is another question I would like to discuss – is NextAuth.js the correct library for my use case? I mean, there is more documentation and examples for @azure/msal-react, it is specialized into this matter, so is it the better option?

Answer:

NextAuth.js is a fine library to use for this.
You can put the accessToken that AzureB2C gives you for the signed-in user into their session JWT in the jwt callback in your NextAuth.js config.
See docs about exactly this use-case here: https://next-auth.js.org/configuration/callbacks#jwt-callback See another example of it in action here: https://github.com/nextauthjs/next-auth-refresh-token-example/blob/57f84dbc50f30233d4ee389c7239212858ecae14/pages/api/auth/%5B…nextauth%5D.js#L67
Once you have it in the session JWT, you can use the getToken() method in Next.js API routes, for example, to retrieve the token and make calls with it, etc.

If you have better answer, please add a comment about this, thank you!