简体   繁体   English

服务器端 Blazor 获取承载令牌

[英]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.使用 .net 核心 3.1.4,我创建了一个使用 Azure 活动目录身份验证的服务器端 blazor 应用程序。 I am using following json with values pointing to my azure active directory.我正在使用以下 json 值指向我的 azure 活动目录。

{
  "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.一切正常意味着我可以使用我的 Azure AD 凭据登录,但在 httpcontext 的请求标头中,我没有获得用于进一步调用我的其他 api 的不记名访问令牌。 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:您可以在ConfigureServices中注册您的 OIDC 中间件并将SaveTokens设置为 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.并参考此代码示例: https://stackoverflow.com/a/59901672/5751404将令牌保存到本地存储以供以后使用。

In the default template you will only get id token via:在默认模板中,您只能通过以下方式获取 id 令牌:

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.由于您只执行response_typeid_token的 OpenID Connect 登录过程,如果您想获取访问令牌以访问另一个 web api,您可以使用Code Flow ,您可以使用代码在OnAuthorizationCodeReceived事件中获取访问令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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