user2845758
user2845758

Reputation: 21

.Net core not able to generate token on server

Startup.cs:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
.AddInMemoryTokenCaches();

My Class:

var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { clientId+"/.default" });

on local accessToken is having value and all works but on Azure server it returns Null.

I am getting below exception:

One or more errors occurred. (Value cannot be null. (Parameter 'headers'))System.AggregateException: One or more errors occurred. (Value cannot be null. (Parameter 'headers')) ---> System.ArgumentNullException: Value cannot be null. (Parameter 'headers') at Microsoft.Identity.Web.Throws.ArgumentNullException(String paramName) at Microsoft.Identity.Web.AppServicesAuthenticationInformation.GetIdToken(IDictionary2 headers) at Microsoft.Identity.Web.AppServicesAuthenticationTokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions) --- End of inner exception stack trace ---

Upvotes: 0

Views: 207

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 16056

I didn't reproduce your issue in my side but everything working both in local side and in Azure web app. Could you pls take a look at what I have and comparing with yours?

You mentioned Startup.cs so I created a .net core 3.1 app and I also suggest you to upgrade to a newer version of .net as .net core 31 is end of support for microsoft.

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
.AddInMemoryTokenCaches();


services.AddControllersWithViews(options =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
services.AddRazorPages();

In controller, inject ITokenAcquisition and have codes below:

var accessToken2 = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "client_id/.default" });
    var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "api://3743e7c8-ac84-4203-954d-78beed41b2d7/Tiny.Read" });
    ViewBag.token = accessToken;
    ViewBag.token2 = accessToken2;
    return View();

Here I want to say, when we are using GetAccessTokenForUserAsync it should used for generating acccess token on behalf of the user, and when we want to generate access token for our own custom api permission, the format should be api://client_id_exposing_api/permission_name and I'm also confused that why we are able to generate an access token with client_id/.default.

The nuget packages:

 <ItemGroup>
   <PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="3.1.32" />
   <PackageReference Include="Microsoft.Identity.Web" Version="2.15.3" />
   <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.15.3" />
 </ItemGroup>

appsettings.json:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "tenant_id",
  "TenantId": "tenant_id",
  "ClientId": "client_id",
  "ClientSecret": "client_secret",
  "CallbackPath": "/signin-oidc"
},

Then I created an Azure web app in Auzre portal, we are not able to choose .net core 3.1 anymore so I chose .net 6 here.

enter image description here

Don't forget to add redirect url in the Azure ad authentication blade.

enter image description here

and here's my test result.

enter image description here

To troubleshoot your issue, I'm afraid you need to explain more about in my case it works when running localhost but not on Azure, such as the exception messages if it throws exception, some logs if you added. You might enable application insights if needed.

Upvotes: 0

Related Questions