c# - Dotnet core 3.1 和 Angular 9 的 AAD 注册

标签 c# angular azure azure-active-directory asp.net-core-webapi

我需要构建一个简单的 spa( Angular 9)应用程序,并在 Azure Active Directory 注册后使用 dotnet core 3.1。是否有文档或教程如何制作 dotnet core + Angular + AAD auth 简单应用程序?

我找到了这篇文章AAD with angular, dotnet and MSAL ,但今天看来并不现实。

我注册了两个应用程序注册(如文章中所示),并获取了 client app from the sample .

我的 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-app 添加到后端项目中,就像这样:

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": "*"
}

当我运行该项目时,我单击“登录”,一切正常,之后通过注入(inject)的 HTTPClient 的所有请求都包含承载 token 。

但是当我调用任何标有[Authorize]的 Controller 时,它总是返回401。

那么也许某些步骤包含错误?或者是否有文档或教程如何制作 dotnet core + Angular + AAD auth 简单应用程序?至少对于 dotnet 和 Angular 的其他版本来说是这样,但还不算太旧。

谢谢。

最佳答案

您应该在 Angular 应用程序中获取访问 token 才能访问您的 Web API 应用程序。

注册Web api应用程序时,配置Expose an APIAdd a Scope像:api://<cliendID>/api-access ,并在 .net core Web 应用程序中,设置 ClientIdapi://<clientid> .

在 Angular 应用端,可以设置 consentScopes包含您的 Web api 的范围:

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

  • consentScopes :允许客户表达应同意的所需范围。范围可以来自多个资源/端点。在此处传递范围只会同意它,并且在客户端实际调用 API 之前不会获取访问 token

并设置protectedResourceMap包含获取访问 token 的 api 范围:

  • protectedResourceMap :将资源映射到范围 {"https://graph.microsoft.com/v1.0/me ", ["user.read", "mail.send"]}。由 MSAL 在内部使用,用于在 webApi 调用中自动附加 token 。仅 CORS 调用需要这样做。

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

您可以查看 MSAL For Angular document更多细节 。和this code sample适用于 Angular 9 。您可以通过更新 app.module.ts 中的配置来修改代码示例。

更新:

您使用的是Azure AD V2.0,所以管理员应该添加/v2.0在 Web api 中验证 token 时:

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}"
    };


}); 

关于c# - Dotnet core 3.1 和 Angular 9 的 AAD 注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60541368/

相关文章:

c# - WPF 中的运行与内容与文本

javascript - Chrome自动标签丢弃禁用javascript?

rest - Angular2 - Http 服务 - 如何确保我始终拥有实时数据

c# - 如何使用azure函数或逻辑应用程序监视sftp中的多个位置?

c# - 参数类型不可分配给参数类型,它应该是

c# - 每次 Random.Next() 调用时返回所有数字的概率是否相同?

Angular 2 : How to pass a string to a pipe in a Typescript function?

angular - 如何从 Microsoft Teams 应用程序获取 Azure DevOps 的访问 token ?

c# - 从 Asp.Net 站点将数据发送到 EventHub

具有 FromForm 绑定(bind)到 IFormFile 属性的 C# 集成测试 Controller