1
votes

I'm working with a .Net Core Web API and a .Net Core Web MVC Application. They both use Azure AD B2C to authenticate users. But in order to get a response from a HttpRequest from the Web API I need to provide the JWT Access Token from B2C for the signed in user on my web MVC application. Is there a way to obtain this access token inside a controller using the authenticated "User".

I have tried accessing the claims of the signed in user but no luck there, I have also used jwt.ms to review that the B2C workflow works well and that the JWT token is being generated and it works as well. The MVC application is authenticating the user and the web API is working fine with a hardcoded token. I just need to obtain the access token from a signed in user rather than doing it hardcoded.

I expect to be able to get the B2C JWT access token so that I can later on pass it to the Web Api and be able to secure my requests.

3
Another information that might help is that I'm using the B2C template for the .Net Core Web MVC Application that uses AzureADB2C.UI Nuget package to obtain the JWT from Azure.Andre Vigneault

3 Answers

2
votes

After getting some help from the MS AzureADB2C.UI GitHub crew we were able to solve the issue. The issue was that the tokens aren't saved by default on the library, so we needed to configure OIDC to specify that the tokens have to be saved for future use within the application. And so here is the example code of the "Startup" configuration and the example of how to query the "JWT access token" from the controller.

Startup.cs:

    services.Configure(AzureADB2CDefaults.OpenIdScheme, options => {
            options.SaveTokens = true;
    });

Controller:

    string idToken = await HttpContext.GetTokenAsync("id_token");

More information on how was the issue solved can be found on the following link: https://github.com/aspnet/AspNetCore/issues/11424

1
votes

You can refer to this sample application.

It uses the ASP.NET Core Azure AD B2C middleware to authenticate the end user and MSAL.NET to acquire, cache, and refresh the access token.

The access token is acquired in the AzureADB2COpenIdConnectOptionsConfigurator class.

A code example for a controller method referencing the access token is here.

0
votes

Is it the actual token string you need? If so, you can access the headers using the HttpContext within the controller? The HttpContext will have a collection of headers that were passed in