Blazor Azure B2C单机版未在请求中发送授权标头(JWT)

tkclm6bt  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(119)

我有一个Blazor Webassembly应用,它使用Azure B2C对用户进行身份验证和授权。我能够成功登录并生成令牌,但当我尝试调用我的API时,请求标头中没有令牌。
我遵循了以下指南:https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory-b2c?view=aspnetcore-7.0
这是我的程序. cs

var builder = WebAssemblyHostBuilder.CreateDefault(args);

var baseAddress = builder.Configuration.GetValue<string>("BaseUrl");

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddHttpClient("WebAPI", client => client.BaseAddress = new Uri(baseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
    .CreateClient("WebAPI"));

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://{domain}.onmicrosoft.com/{App ID}/Api.Access");
});

await builder.Build().RunAsync();

我是否遗漏了向HttpClient添加令牌的行?

7xllpg7q

7xllpg7q1#

我有一个测试在我的身边,我遇到了你的问题,以及在我的身边,这是我用来生成令牌手动调用API。使用代码我的评论。

@page "/profile"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
@attribute [Authorize]
@inject IAccessTokenProvider TokenProvider
@inject HttpClient Http

<h3>User Profile</h3>
<button @onclick="call">
    call api
</button>
<div>@result</div>

@code {

    private string result = "no data now";

    private async Task call()
    {
        try
        {
            result = await Http.GetStringAsync("https://localhost:7018/WeatherForecast");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }

        //var http = new HttpClient();
        //http.BaseAddress = new Uri("https://localhost:7018/WeatherForecast");

        //var tokenResult = await TokenProvider.RequestAccessToken(
        //    new AccessTokenRequestOptions
        //        {
        //            Scopes = new[] { "api://xxxx/Tiny.Read" }
        //        });

        //if (tokenResult.TryGetToken(out var token))
        //{
        //    http.DefaultRequestHeaders.Add("Authorization",
        //        $"Bearer {token.Value}");
        //    result = await http.GetStringAsync("https://localhost:7018/WeatherForecast");
        //}
    }
}

相关问题