久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何配置.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 應用注冊(您可能不需要更改).以下是相關(guān)文檔:注冊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"部分下的授權(quán)應用程序.我們將使用身份驗證流程以不同方式處理.
  • 不需要重定向 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 權(quán)限"下,為您的前端應用授予對后端 API 的訪問權(quán)限:
    • 在API 權(quán)限"下點擊添加權(quán)限",然后點擊我的 API"標簽
    • 找到您的后端應用程序并選擇適當?shù)姆秶?
    • 點擊添加權(quán)限"
    • 可選擇為您的 API 授予同意

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

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

    后端應用注冊公開一個api

    前端應用注冊認證

    前端應用注冊api權(quán)限

    現(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 中的相關(guān)代碼:

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

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

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

相關(guā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 令牌授權(quán)不起作用)
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 超時)
主站蜘蛛池模板: 一区二区三区国产精品 | 中文字幕亚洲欧美 | 久久久婷婷 | 久久久免费在线观看 | 精品国产乱码久久久久久图片 | 久热精品在线播放 | 毛片99| h视频在线免费看 | 亚洲www啪成人一区二区 | 黄色国产在线播放 | 91精品久久久久久久99 | 国产一区二区三区久久久久久久久 | 欧美a免费| 成人免费在线播放视频 | 日韩在线中文字幕 | 国产探花在线精品一区二区 | 激情福利视频 | 久久三级av | 一级毛片在线看 | 九七午夜剧场福利写真 | 成人国产精品久久 | 91人人看 | 美女爽到呻吟久久久久 | 精品日韩一区二区三区av动图 | 最近最新中文字幕 | 黑人粗黑大躁护士 | 风间由美一区二区三区在线观看 | 欧美一级二级视频 | 五十女人一级毛片 | 国产一区二区三区四区三区四 | 国产精品69久久久久水密桃 | 成人精品一区二区三区中文字幕 | 欧美三级视频 | 精品久久久久久亚洲综合网 | 国产精品视频区 | 草樱av | 找个黄色片 | 天天干.com | 免费观看一级特黄欧美大片 | 日韩毛片免费视频 | 91佛爷在线观看 |