使用带有 Angular 和 C# webapi 的 MSAL 进行访问令牌身份验证的问题

问题描述 投票:0回答:1

我需要授权 Angular 用户访问我受保护的 WebAPI。 我在 C# 后端,需要使用 MSAL 授权登录(角度前端创建会话并获取访问令牌)。我需要验证 C# Web api 中的令牌以确定令牌是否有效。我将从 Angular 前端获取用户的电子邮件和访问令牌。

我搜索使用以下代码默默检查身份验证,但我找不到如何创建帐户

 var result = await app.AcquireTokenSilent(scopes, userAccount)
            .ExecuteAsync();

创建帐户需要以下参数,但它不会返回任何结果。

var accounts = await app.GetAccountsAsync();
    var account = accounts.FirstOrDefault(); 
    

在此之前,代码如下所示

var app = PublicClientApplicationBuilder
        .Create(clientId)
        .WithAuthority("https://login.microsoftonline.com/TenantID")
        .WithRedirectUri("redirect URL")
        .Build();
c# authentication azure-active-directory asp.net-core-webapi msal
1个回答
0
投票

我需要授权 Angular 用户访问我受保护的 WebAPI。

这意味着您需要将 AAD 集成到您的 Angular 应用程序中,并且还需要使用 AAD 来保护您的 Web API。这将使您的 Angular 提供登录功能并生成访问令牌来访问 API,并且您的 API 应通过 AAD 验证令牌并决定请求是否可以访问 API 或返回 401。

我不知道角度,所以我可以在这里分享一个示例。

首先,就像@juunas所说,你需要配置JWT身份验证。您还可以查看本教程。它需要在 AAD 中公开 API,并且您的 API 应用程序中必须有以下代码。使用下面的代码,如果请求没有正确的访问令牌,具有

[Authorize]
属性的 API 将返回 401 响应。

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "allowall",
                      policy =>
                      {
                          policy.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod();
                      });
});
builder.Services.AddControllers();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

接下来,对于 Angular 应用程序,按照这个官方文档中的示例,我们将得到一个允许我们登录并调用 ms graph api 的应用程序。

如果我们将

protectedResourceMap
中的配置
app.module.ts
更改为
protectedResourceMap.set(GRAPH_ENDPOINT, ['user.read']);
更改为
protectedResourceMap.set("https://localhost:7072/WeatherForecast", ['api://client-id/custom_api_permission_name']);
,并将
this.http.get(GRAPH_ENDPOINT)
中的
this.http.get("https://localhost:7072/WeatherForecast")
更改为
profile.component.ts
,我们将更改使用经过身份验证的凭据调用受保护 Web api 的请求。

© www.soinside.com 2019 - 2024. All rights reserved.