简体   繁体   中英

Server side Blazor get bearer token

With .net core 3.1.4, I have created a server side blazor app which uses Azure active directory authentication. I am using following json with values pointing to my azure active directory.

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "contoso.onmicrosoft.com",
    "TenantId": "e86c78e2-8bb4-4c41-aefd-918e0565a45e",
    "ClientId": "41451fa7-82d9-4673-8fa5-69eff5a761fd",
  }
}

All works perfect means I can login with my Azure AD credentials but in the httpcontext's request headers, I do not get bearer access token to use for making call to my other apis further. How to get bearer access token for the logged in user in this case?

Thanks, Jay

You can register your OIDC middleware inside ConfigureServices and set SaveTokens to true:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{       
    options.SaveTokens = true;
});

And refer to this code sample: https://stackoverflow.com/a/59901672/5751404 to save tokens to localstorage for later use.

In the default template you will only get id token via:

var id_token = await HttpContext.GetTokenAsync("id_token");

Since you are only performing OpenID Connect sign-in process which response_type is id_token , if you want to acquire access token for accessing another web api, you can use Code Flow , you can use code to acquire access token in OnAuthorizationCodeReceived event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM