【问题标题】:Blazor WASM attach token to HTTP ClientBlazor WASM 将令牌附加到 HTTP 客户端
【发布时间】: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...

我已经尝试了最初提到的指南中的所有变体,但我没有成功将不记名令牌附加到调用中的任何一个。

我错过了什么?

【问题讨论】:

    标签: blazor blazor-webassembly


    【解决方案1】:

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

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

    【讨论】:

    • "我必须将 CustomAuthorizationMessageHandler 添加到我的客户端。"这不是问题。您创建的 HttpClient 对象未配置为 Main 方法中的对象的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 2021-02-27
    • 2021-02-03
    • 1970-01-01
    • 2020-12-21
    • 2021-04-05
    • 2020-07-27
    • 2020-05-17
    相关资源
    最近更新 更多