Blazor独立WebAssembly代表登录用户调用安全核心API



我在AAD中设置了一个安全的API应用程序,其中包含两个作用域。我还有一个独立的Blazor客户端,我想从它向我的API发出请求。我有一个用户可以访问我的API作用域。我的客户端已将权限委派给我的API-所有作用域。

当我添加app.MapControllers().AllowAnonymous();时,我正在Blazor客户端中获取数据。一切都很好。当我去掉那条线时,我得到的是404。我已经尝试了5天来解决这个问题,现在我辞职了。我可以使用我在AAD中创建的用户登录到应用程序,当我提出请求时,我可以在fiddler中看到承载令牌在标头中。。。我总是得到404,甚至没有401或403。

这是我的Api配置:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

这是我的客户端配置:

builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
});
builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
builder.Services.AddHttpClient("WebAPI",
client => client.BaseAddress = new Uri("https://localhost:5101/"))
.AddHttpMessageHandler<CustomAuthorizationMessageHandler>();

和处理程序:

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "https://localhost:5101/" },
scopes: new[] { "api://38019b82-84d0-40cc-a2cd-155f2d8b7757/API.RO1" });
}
}

我在我的页面上调用api如下:

var client = ClientFactory.CreateClient("WebAPI");
entries = await client.GetFromJsonAsync<List<TimeSeriesEntry>>("/api/tds/2022-08-06");

你能告诉我这个配置是否有明显的问题吗?

您不应该删除整行app.MapControllers().AllowAnonymous();app.MapControllers();对于web api的工作至关重要。

最新更新