Blazor WASM 将令牌附加到 HTTP 客户端

时间:2021-01-03 09:51:13

标签: blazor blazor-webassembly

我花了很多时间尝试使用不记名令牌进行身份验证,以便从我的本地主机开发到在授权标头中需要不记名令牌的 Azure 函数 API。

在指南中发现 here 如果我正确阅读了文档,则令牌应自动附加到任何具有我为函数应用 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"));

我使用函数应用所在的 Azure AD 进行身份验证:

builder.Services.AddMsalAuthentication(options =>
{
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
});

我的 Index.razor 页面有 @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...enter image description here

我已经尝试了最初提到的指南中的所有变体,但我没有成功地将不记名令牌附加到呼叫中。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

最后,重新阅读这篇文章:Automatically Attaching Access Token to HTTP Client in Blazor wasm 第 5 次解决了我的问题。

我必须将 CustomAuthorizationMessageHandler 添加到我的客户端。