【发布时间】:2021-11-30 23:08:36
【问题描述】:
我正在尝试让 Azure AD 身份验证在 Blazor WASM 应用程序和我在本地运行但在不同端口上运行的另一个 API 之间工作。我需要这两个应用程序来使用 Azure 登录,但我只希望用户必须在 Blazor 应用程序上登录一次,然后将这些凭据传递给 API。
我已经在门户中为这两个应用程序设置了应用程序注册,创建了重定向 URL,使用范围公开了 API,我可以成功登录到 blazor 应用程序并使用 @context.User.Identity.Name 查看我的名字.
但是,当它尝试调用 API 时,我收到 401 错误,并且它没有遇到 API 中的任何断点(可能是因为在 http 请求中没有传递身份验证)。
我在 Blazor 应用程序中的代码设置了一个 http 客户端,并将基地址设置为 API:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddHttpClient("APIClient", client => client.BaseAddress = new Uri("https://localhost:11001"))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("APIClient"));
builder.Services.AddMsalAuthentication<RemoteAuthenticationState, CustomUserAccount>(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("api://d3152e51-9f5e-4ff7-85f2-8df5df5e2b2e/MyAPI");
//options.UserOptions.RoleClaim = "appRole";
});
await builder.Build().RunAsync();
}
在我的 API 中,我只是在类上设置了 Authorize 属性,最终也需要角色:
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class CarController
然后,在我的 Blazor 组件中,注入 http 工厂并尝试发出请求:
@inject IHttpClientFactory _factory
...
private async Task RetrieveCars()
{
var httpClient = _factory.CreateClient("APIClient");
HttpResponseMessage response = await httpClient.GetAsync("https://localhost:11001/api/cars");
var resp = await response.Content.ReadAsStringAsync();
cars = JsonSerializer.Deserialize<List<Car>>(resp);
}
但这会返回 401 错误。我还尝试了一些不同的变体,比如只注入一个 http 客户端(@inject HttpClient Http),但似乎没有任何东西将我的授权添加到 API 调用中。 options.UserOptions.RoleClaim 也在 AddMsalAuthentication 部分中被注释掉,因为我不确定是否需要它,但它在有或没有它的情况下都不起作用。
谁能解释我做错了什么以及我应该使用什么代码?
【问题讨论】:
-
添加范围后是否同意门户中的 api 权限?如果完成,请提供完整的错误详细信息。
标签: azure-active-directory blazor blazor-webassembly azure-authentication asp.net-blazor