![](/img/trans.png)
[英]How do I get the access token from a blazor (server-side) web app?
[英]Why is the returned access token null in a Blazor Server-Side application?
这个问题已经在 SO 上提出了几次,但这些答案似乎都不适用于我的情况。
如何从 blazor(服务器端)web 应用程序获取访问令牌?
Blazor 服务器 - 从当前登录用户获取 AAD 访问令牌
我有一个在 .net6 上运行的.net6
应用程序(服务器端)。 它连接到我的 Azure Active Directory。 我可以成功地向 AAD 验证自己并获取ClaimsPrincipal
实例。
以下是设置 AAD 的Program.cs
文件的摘录:
[...]
builder.Services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
;
builder.Services
.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true;
});
[...]
与AzureAd
部分相关的配置包含以下信息:
[...]
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "XXX.com",
"TenantId": "5dXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"ClientId": "26XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"CallbackPath": "/signin-oidc"
}
[...]
根据前面的答案,一旦我成功通过身份验证,文件_Host.cshtml
中的以下调用应该会给我一个有效的访问令牌,但在我的情况下并非如此:
问题
为什么在我的 Blazor 应用程序中返回的访问令牌null
?
更新 1
我已经在启动文件中看到了使用这些额外的 2 个调用的答案:
[...]
builder.Services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { "openid" })
.AddInMemoryTokenCaches()
;
我看没有任何变化。
如果您想为您的下游 API 请求令牌,TokenAcquisition 是 go 的方式:
using Microsoft.Identity.Web;
//...
string token = await TokenAcquisition.GetAccessTokenForUserAsync(new string[] {apiScope});
结合 IDownstreamWebApi,您甚至不必将令牌保存为字符串,它会在调用 api 时被分配:
protected readonly IDownstreamWebApi _webApi; // Injected
protected readonly ITokenAcquisition TokenAcquisition; // Injected
// ...
public async Task CallApi(){
await TokenAcquisition.GetAccessTokenForUserAsync(new string[] {apiScope});
var response = await _webApi.CallWebApiForUserAsync("apiName", options => ... );
}
和 appsettings 结构:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "<AD domain>",
"TenantId": "<TenantId>",
"ClientId": "<ClientId of this registered app>",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath": "/signout-callback-oidc",
"ClientSecret": "<Secret of registered API>"
},
"API": {
"APIScope": "api://<APIAppID>/access_as_user",
"Scopes": "api://<APIAppID/access_as_user",
"BaseUrl": "https://localhost:7003/"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.