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 超時)
主站蜘蛛池模板: 贵州水玻璃_-贵阳花溪闽兴水玻璃厂 | 一航网络-软件测评官网| 上海办公室装修,办公楼装修设计,办公空间设计,企业展厅设计_写艺装饰公司 | elisa试剂盒-PCR试剂盒「上海谷研实业有限公司」 | 喷漆房_废气处理设备-湖北天地鑫环保设备有限公司 | 房间温控器|LonWorks|海思| 高低温万能试验机-复合材料万能试验机-馥勒仪器 | 【星耀裂变】_企微SCRM_任务宝_视频号分销裂变_企业微信裂变增长_私域流量_裂变营销 | 技德应用| 联系我们老街华纳娱乐公司官网19989979996(客服) | 深圳标识制作公司-标识标牌厂家-深圳广告标识制作-玟璟广告-深圳市玟璟广告有限公司 | 法兰螺母 - 不锈钢螺母制造厂家 - 万千紧固件--螺母街 | KBX-220倾斜开关|KBW-220P/L跑偏开关|拉绳开关|DHJY-I隔爆打滑开关|溜槽堵塞开关|欠速开关|声光报警器-山东卓信有限公司 | 高精度-恒温冷水机-螺杆式冰水机-蒸发冷冷水机-北京蓝海神骏科技有限公司 | 瓶盖扭矩测试仪-瓶盖扭力仪-全自动扭矩仪-济南三泉中石单品站 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 锂电池生产厂家-电动自行车航模无人机锂电池定制-世豹新能源 | 直线模组_滚珠丝杆滑台_模组滑台厂家_万里疆科技 | 微水泥_硅藻泥_艺术涂料_艺术漆_艺术漆加盟-青岛泥之韵环保壁材 武汉EPS线条_EPS装饰线条_EPS构件_湖北博欧EPS线条厂家 | 骨密度仪-骨密度测定仪-超声骨密度仪-骨龄测定仪-天津开发区圣鸿医疗器械有限公司 | 礼至家居-全屋定制家具_一站式全屋整装_免费量房设计报价 | 章丘丰源机械有限公司 - 三叶罗茨风机,罗茨鼓风机,罗茨风机 | 阀门智能定位器_电液动执行器_气动执行机构-赫尔法流体技术(北京)有限公司 | 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 快速门厂家批发_PVC快速卷帘门_高速门_高速卷帘门-广州万盛门业 快干水泥|桥梁伸缩缝止水胶|伸缩缝装置生产厂家-广东广航交通科技有限公司 | 丹佛斯变频器-Danfoss战略代理经销商-上海津信变频器有限公司 | 工业PH计|工业ph酸度计|在线PH计价格-合肥卓尔仪器仪表有限公司 济南画室培训-美术高考培训-山东艺霖艺术培训画室 | U拓留学雅思一站式服务中心_留学申请_雅思托福培训 | 斗式提升机,斗式提升机厂家-淄博宏建机械有限公司 | 高温高压釜(氢化反应釜)百科 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 车载加油机品牌_ 柴油加油机厂家 | 耐酸碱泵-自吸耐酸碱泵型号「品牌厂家」立式耐酸碱泵价格-昆山国宝过滤机有限公司首页 | 外观设计_设备外观设计_外观设计公司_产品外观设计_机械设备外观设计_东莞工业设计公司-意品深蓝 | 塑钢课桌椅、学生课桌椅、课桌椅厂家-学仕教育设备首页 | 武汉创亿电气设备有限公司_电力检测设备生产厂家| 全钢实验台,实验室工作台厂家-无锡市辰之航装饰材料有限公司 | 卫生型双针压力表-高温防腐差压表-安徽康泰电气有限公司 | 我车网|我关心的汽车资讯_汽车图片_汽车生活! | 北京易通慧公司从事北京网站优化,北京网络推广、网站建设一站式服务商-北京网站优化公司 | 网站建设,北京网站建设,北京网站建设公司,网站系统开发,北京网站制作公司,响应式网站,做网站公司,海淀做网站,朝阳做网站,昌平做网站,建站公司 |