Dotnet核心3.1和Angular 9的AAD注册



我需要使用Azure Active Directory注册来构建一个简单的spa(angular 9(应用程序,该应用程序的背面是dotnet core 3.1。有没有关于如何使dotnet core+angular+AAD auth成为简单应用程序的文档或教程?

我发现文章AAD有angular,dotnet和MSAL,但它似乎不是今天的实际。

我注册了两个应用程序注册(如文章所示(,并从示例中获取了客户端应用程序。

我的app.module.ts包含:

function MSALConfigFactory(): Configuration {
return {
auth: {
clientId: '<client-id-of-frontend-app-registration>',
authority: "https://login.microsoftonline.com/<tenant-id>",
validateAuthority: true
// redirectUri: "http://localhost:4200/",
// postLogoutRedirectUri: "http://localhost:4200/",
// navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: isIE, // set to true for IE 11
},
};
}

之后,我创建了后端项目:

dotnet new webapi --client-id <client-id-of-backend-app-registration> --tenant-id <tenant-id> --domain microsoft.onmicrosoft.com --auth SingleOrg

并将angular应用程序添加到后端项目中,就像使用一样

dotnet new angular

所以appsettings.json包含:

{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/ ",
"Domain": "microsoft.onmicrosoft.com",
"TenantId": "<tenant-id>",
"ClientId": "<client-id-of-backend-app-registration>"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

当我运行该项目时,我单击"登录",一切都正常,然后通过注入的HTTPClients的所有请求都包含Bearer令牌。

但当我调用任何标有[授权]的控制器时,它总是返回401。

所以,也许有些步骤包含错误?或者有文档或教程如何使dotnet core+angular+AAD auth成为简单的应用程序?至少对于另一个版本的dotnet和angular来说,但不会太旧。

谢谢。

您应该在Angular应用程序中获取访问令牌来访问您的web api应用程序。

注册web api应用程序时,将Expose an APIAdd a Scope配置为:api://<cliendID>/api-access,在.net核心web应用程序中,将ClientId设置为api://<clientid>

在Angular应用程序端,您可以将consentScopes设置为包含web api的作用域:

consentScopes: [ "api://<clientid>/api-access" ]

  • consentScopes:允许客户端表达需要同意的范围。作用域可以来自多个资源/终结点。在这里传递作用域只会同意它,并且在客户端实际调用API之前不会获取访问令牌

并将protectedResourceMap设置为包括获取访问令牌的api作用域:

  • protectedResourceMap:资源到作用域的映射{"https://graph.microsoft.com/v1.0/me",["user.read","mail.send"]}。由MSAL内部用于在webApi调用中自动附加令牌。这仅对CORS调用是必需的

例如:export const protectedResourceMap:[string, string[]][]=[['https://localhost:44388/api/values', ['api://59b02905-8b6b-4665-a702-321e97392416/api-access']] ];

您可以查看MSAL For Angular文档以了解更多详细信息。这个代码示例适用于Angular 9。您可以通过更新app.module.ts.中的配置来修改代码示例

更新:

您正在使用Azure AD V2.0,因此授权机构在验证web api:中的令牌时应添加/v2.0

services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
{
// This is a Microsoft identity platform web API.
options.Authority += "/v2.0";
// The web API accepts as audiences both the Client ID (options.Audience) and api://{ClientID}.
options.TokenValidationParameters.ValidAudiences = new []
{
options.Audience,
$"api://{options.Audience}"
};

}); 

这是为寻求完整实现的人准备的https://www.c-sharpcorner.com/article/part-1-integrate-or-authenticate-your-asp-net-web-apis-and-angular-application/

最新更新