【发布时间】:2021-01-03 18:29:28
【问题描述】:
我花了很多时间尝试使用不记名令牌进行身份验证,以便从我的本地主机开发到需要授权标头中的不记名令牌的 Azure 函数 API。
在找到here 的指南中,如果我正确阅读了文档,令牌应该自动附加到具有我为我的 Function App API 配置的基地址的任何客户端。
我的program.cs 中有这个:
builder.Services.AddHttpClient("ServerAPI",
client => client.BaseAddress = new Uri("https://myapp.azurewebsites.net"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("ServerAPI"));
我使用 Function App 所在的 Azure AD 进行身份验证:
builder.Services.AddMsalAuthentication(options =>
{
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
});
我的Index.razorpage 有@attribute [Authorize] 并得到正确验证。根据 Edge 中的开发者工具,令牌被授予并保存在会话存储和本地存储中。
问题是,不记名令牌未添加到我在index.razor 文件中的代码中使用的客户端。我有这个代码:
private async Task GetMyData()
{
var client = HttpClientFactory.CreateClient("ServerAPI");
profile = await client.GetFromJsonAsync<UserProfile[]>("api/GetMyData");
}
但是当我按下这个按钮时:
<button class="btn btn-primary" @onclick="GetMyData">Get Data</button>
调用按预期执行,但不记名令牌未添加到标头,因此执行失败。
我希望在这里某处看到authorization: bearer ey34h7two4ntw3yt4m...:
我已经尝试了最初提到的指南中的所有变体,但我没有成功将不记名令牌附加到调用中的任何一个。
我错过了什么?
【问题讨论】: