pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何配置.net core angular azure AD 身份驗證?

How to configure .net core angular azure AD authentication?(如何配置.net core angular azure AD 身份驗證?)
本文介紹了如何配置.net core angular azure AD 身份驗證?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我目前正在將 Azure AD 身份驗證集成到 Angular - .Net core 3.1 項目.這是一個從 Visual Studio 2019 模板(ASP.NET Core Web App)生成的項目.
在 Azure 門戶中,我注冊了 2 個應用程序并由 MS教程和這個.

I'm currently working on Azure AD authenticaton integration to Angular - .Net core 3.1 project. This is a project which was generated from Visual Studio 2019 template (ASP.NET Core Web App).
In Azure portal, I registered 2 application and configured by MS tutorial and this.

兩個注冊的應用程序:

  1. frontend_app(客戶端 ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx16e3)
  2. backend_api(客戶端ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxfcc1)

但我只發(fā)布了一個 App 服務,其中包含 SPA 和 API.登錄后,我得到一個令牌,它附加到每個使用 MSAL 攔截器的 api 調(diào)用.

But I published only one App service, which contains both SPA and API. After login, I got a token, which append to every api call with MSAL interceptor.

問題是所有的調(diào)用返回都是:401,由于觀眾無效".在 auth 令牌中,觀眾重視 frontend_app 的客戶端 ID.

The problem is all of the calls return is: 401, due to 'audience is invalid'. in the auth token the audience value the client id of frontend_app.

我該如何解決才能接受觀眾?只為一個應用服務使用2個應用注冊是否正確?

How can I solve to accept the the audience? Is it correct to use 2 app registration for only one app service?

推薦答案

我遇到了和你一樣的問題,相信我已經(jīng)找到了解決方案.我最初遵循的所有指南都使用隱式流程.正如卡爾在他的回答中指出的那樣(我認為這不能正確解決您的問題),有一個 auth flow 這是推薦的方式.不幸的是,所有示例和指南中的標準 MSAL 庫都是 1.x,不支持身份驗證流程.相反,您需要使用 MSAL.js 2.0.問題是角度庫仍在 阿爾法

I was having the same problem as you and believe I have come up with a solution. All the guides I originally followed were using the implicit flow. As Carl pointed out in his answer (which I don't believe properly addresses your issue), there's an auth flow which is the recommended way to go. Unfortunately the standard MSAL libraries from all the samples and guides are 1.x and don't support auth flow. Instead, you'll need to use MSAL.js 2.0. The catch is that the angular library is still in alpha

所以,這就是我所做的一切.我正在使用帶有 ASP.NET Core 3.1 后端的 Angular 10 前端.

So, here's what I did to make it all work. I'm using an Angular 10 front-end with an ASP.NET Core 3.1 backend.

首先,您創(chuàng)建后端 api 應用注冊(您可能不需要更改).以下是相關文檔:注冊Web API.重要說明:

First, you create your backend api app registration (which you may not need to change). Here's the documentation for that: Register Web API. Important notes:

  • 使用此方法,您無需將前端客戶端 ID 添加為公開 API"部分下的授權應用程序.我們將使用身份驗證流程以不同方式處理.
  • 不需要重定向 URI,因為您的后端不會讓用戶登錄
  • 您至少需要一個示波器才能正常工作

然后按照 MSAL.js 2.0 文檔來創(chuàng)建前端應用注冊.重要說明如下:

Then follow the MSAL.js 2.0 documentation to create the frontend app registration. The important notes are as follows:

  • 確保選擇 SPA 平臺并輸入有效的重定向 URI
  • 請勿選中隱式授予"復選框
  • 在API 權限"下,為您的前端應用授予對后端 API 的訪問權限:
    • 在API 權限"下點擊添加權限",然后點擊我的 API"標簽
    • 找到您的后端應用程序并選擇適當?shù)姆秶?
    • 點擊添加權限"
    • 可選擇為您的 API 授予同意

    您的應用注冊應類似于以下內(nèi)容:

    Here's what your app registrations should look similar to:

    后端應用注冊公開一個api

    前端應用注冊認證

    前端應用注冊api權限

    現(xiàn)在是代碼.對于您的 Angular 應用,首先安裝必要的模塊:

    Now for the code. For your angular app, first install the necessary modules:

    npm install @azure/msal-browser @azure/msal-angular@alpha
    

    然后將其添加到您的應用模塊中:

    Then add this to your app module:

    import { BrowserModule } from '@angular/platform-browser';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { APP_INITIALIZER, NgModule } from '@angular/core';
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    import { tap } from 'rxjs/operators';
    import {
      IPublicClientApplication,
      PublicClientApplication,
      InteractionType,
      BrowserCacheLocation,
      LogLevel,
    } from '@azure/msal-browser';
    import {
      MsalGuard,
      MsalInterceptor,
      MsalBroadcastService,
      MsalInterceptorConfiguration,
      MsalModule,
      MsalService,
      MSAL_GUARD_CONFIG,
      MSAL_INSTANCE,
      MSAL_INTERCEPTOR_CONFIG,
      MsalGuardConfiguration,
    } from '@azure/msal-angular';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    
    const PROTECTED_RESOURCE_MAP: Map<string, Array<string>> = new Map([
      ['https://graph.microsoft.com/v1.0/me', ['user.read']],
      [
        'api/admin/users',
        ['api://<backend app id>/access_as_admin'],
      ],
    ]);
    
    const IS_IE =
      window.navigator.userAgent.indexOf('MSIE ') > -1 ||
      window.navigator.userAgent.indexOf('Trident/') > -1;
    
    export function loggerCallback(logLevel, message) {
      console.log(message);
    }
    
    export function MSALInstanceFactory(): IPublicClientApplication {
      return new PublicClientApplication({
        auth: {
          clientId: '<frontend app id>',
          authority:
            'https://login.microsoftonline.com/<azure ad tenant id>',
          redirectUri: 'http://localhost:4200',
          postLogoutRedirectUri: 'http://localhost:4200/#/logged-out',
        },
        cache: {
          cacheLocation: BrowserCacheLocation.LocalStorage,
          storeAuthStateInCookie: IS_IE, // set to true for IE 11
        },
        system: {
          loggerOptions: {
            loggerCallback,
            logLevel: LogLevel.Verbose,
            piiLoggingEnabled: false,
          },
        },
      });
    }
    
    export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
      return {
        interactionType: InteractionType.Redirect,
        protectedResourceMap: PROTECTED_RESOURCE_MAP,
      };
    }
    
    export function MSALGuardConfigFactory(): MsalGuardConfiguration {
      return {
        interactionType: InteractionType.Redirect,
      };
    }
    
    export function initializeApp(appConfig: AppConfigService) {
      const promise = appConfig
        .loadAppConfig()
        .pipe(tap((settings: IAppConfig) => {}))
        .toPromise();
      return () => promise;
    }
    
    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        HttpClientModule,
        MsalModule,
      ],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: MsalInterceptor,
          multi: true,
        },
        {
          provide: MSAL_INSTANCE,
          useFactory: MSALInstanceFactory,
        },
        {
          provide: MSAL_GUARD_CONFIG,
          useFactory: MSALGuardConfigFactory,
        },
        {
          provide: MSAL_INTERCEPTOR_CONFIG,
          useFactory: MSALInterceptorConfigFactory,
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService,
      ],
      bootstrap: [AppComponent],
    })
    export class AppModule {}
    

    然后您可以簡單地將 MsalGuard 扔到您想要保護的任何路線上.

    Then you can simply toss the MsalGuard onto any route you want to protect.

    對于后端,首先安裝 Microsoft.Identity.Web 包:

    For the backend, first install the Microsoft.Identity.Web package:

    dotnet add package Microsoft.Identity.Web --version 1.3.0
    

    這是我的 Startup.cs 中的相關代碼:

    Here's the relevant code in my Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
      // other stuff...
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(options =>
        {
          Configuration.Bind("AzureAd", options);
        })
        .AddInMemoryTokenCaches();
    
      services.AddCors((options =>
      {
        options.AddPolicy("FrontEnd", builder =>
          builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
      }));
      // other stuff...
    }
     
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      // other stuff...
      app.UseCors("FrontEnd");
      app.UseAuthentication();
      app.UseAuthorization();
      // other stuff...
    }
    

    appsettings.json 包含:

    appsettings.json contains:

    "AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "Domain": "<azure ad domain>",
      "TenantId": "<azure ad tenant id>",
      "ClientId": "<backend app id>"
    }
    

    這篇關于如何配置.net core angular azure AD 身份驗證?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

    【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
ASP Core Azure Active Directory Login use roles(ASP Core Azure Active Directory 登錄使用角色)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發(fā)技
.Net Core 2.0 - Get AAD access token to use with Microsoft Graph(.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用)
Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調(diào)用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
主站蜘蛛池模板: 广州印刷厂_广州彩印厂-广州艺彩印务有限公司 | 地埋式垃圾站厂家【佳星环保】小区压缩垃圾中转站转运站 | 沧州友城管业有限公司-内外涂塑钢管-大口径螺旋钢管-涂塑螺旋管-保温钢管生产厂家 | 货车视频监控,油管家,货车油管家-淄博世纪锐行电子科技 | 等离子表面处理机-等离子表面活化机-真空等离子清洗机-深圳市东信高科自动化设备有限公司 | 散热器-电子散热器-型材散热器-电源散热片-镇江新区宏图电子散热片厂家 | 浙江筋膜枪-按摩仪厂家-制造商-肩颈按摩仪哪家好-温州市合喜电子科技有限公司 | 搅拌磨|搅拌球磨机|循环磨|循环球磨机-无锡市少宏粉体科技有限公司 | 辽宁资质代办_辽宁建筑资质办理_辽宁建筑资质延期升级_辽宁中杭资质代办 | wika威卡压力表-wika压力变送器-德国wika代理-威卡总代-北京博朗宁科技 | 科昊仪器超纯水机系统-可成气相液氮罐-美菱超低温冰箱-西安昊兴生物科技有限公司 | 衡阳耐适防护科技有限公司——威仕盾焊接防护用品官网/焊工手套/焊接防护服/皮革防护手套 | 防火窗_耐火窗_防火门厂家_防火卷帘门-重庆三乐门业有限公司 | 无菌水质袋-NASCO食品无菌袋-Whirl-Pak无菌采样袋-深圳市慧普德贸易有限公司 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 长沙广告公司|长沙广告制作设计|长沙led灯箱招牌制作找望城湖南锦蓝广告装饰工程有限公司 | 消泡剂_水处理消泡剂_切削液消泡剂_涂料消泡剂_有机硅消泡剂_广州中万新材料生产厂家 | 土壤墒情监测站_土壤墒情监测仪_土壤墒情监测系统_管式土壤墒情站-山东风途物联网 | 中央空调温控器_风机盘管温控器_智能_液晶_三速开关面板-中央空调温控器厂家 | 高楼航空障碍灯厂家哪家好_航空障碍灯厂家_广州北斗星障碍灯有限公司 | 冷藏车厂家|冷藏车价格|小型冷藏车|散装饲料车厂家|程力专用汽车股份有限公司销售十二分公司 | 无压烧结银_有压烧结银_导电银胶_导电油墨_导电胶-善仁(浙江)新材料 | 石英砂矿石色选机_履带辣椒色选机_X光异物检测机-合肥幼狮光电科技 | 食品无尘净化车间,食品罐装净化车间,净化车间配套风淋室-青岛旭恒洁净技术有限公司 | 亚克隆,RNAi干扰检测,miRNA定量检测-上海基屹生物科技有限公司 | 电子元器件呆滞料_元器件临期库存清仓尾料_尾料优选现货采购处理交易商城 | 乐考网-银行从业_基金从业资格考试_初级/中级会计报名时间_中级经济师 | 真石漆,山东真石漆,真石漆厂家,真石漆价格-山东新佳涂料有限公司 | 明渠式紫外线杀菌器-紫外线消毒器厂家-定州市优威环保 | 防火卷帘门价格-聊城一维工贸特级防火卷帘门厂家▲ | 沈阳真空机_沈阳真空包装机_沈阳大米真空包装机-沈阳海鹞真空包装机械有限公司 | 谷歌关键词优化-外贸网站优化-Google SEO小语种推广-思亿欧外贸快车 | 济宁工业提升门|济宁电动防火门|济宁快速堆积门-济宁市统一电动门有限公司 | 保定市泰宏机械制造厂-河北铸件厂-铸造厂-铸件加工-河北大件加工 | 灌装封尾机_胶水灌装机_软管灌装封尾机_无锡和博自动化机械制造有限公司 | 打包钢带,铁皮打包带,烤蓝打包带-高密市金和金属制品厂 | 原色会计-合肥注册公司_合肥代理记账公司_营业执照代办 | 陕西视频监控,智能安防监控,安防系统-西安鑫安5A安防工程公司 | 陕西鹏展科技有限公司 | 丝杆升降机-不锈钢丝杆升降机-非标定制丝杆升降机厂家-山东鑫光减速机有限公司 | Copeland/谷轮压缩机,谷轮半封闭压缩机,谷轮涡旋压缩机,型号规格,技术参数,尺寸图片,价格经销商 CTP磁天平|小电容测量仪|阴阳极极化_双液系沸点测定仪|dsj电渗实验装置-南京桑力电子设备厂 |