1. 程式人生 > >Azure AD(五)使用多租戶應用程式模式讓任何 Azure Active Directory 使用者登入

Azure AD(五)使用多租戶應用程式模式讓任何 Azure Active Directory 使用者登入

一,引言

距離上次分享關於 “Azure AD" 的知識過去差不多2個多月了, 今天最近剛好也是學習,分享一下關於Azure AD 使用多租戶應用程式模式讓任何 Azure Active Directory 使用者登入,之前僅僅都是在當初租戶的使用者或者受邀來賓來訪問和使用我們的api資源的。今天我們將以下關於只要擁有微軟 的工作/學校賬號的使用者都可以使用我們受AD保護的 API 資源。接下來就開始我們今天的分享 

--------------------我是分割線--------------------

1,Azure AD(一)入門認識

2,Azure AD(二)呼叫受Microsoft 標識平臺保護的 ASP.NET Core Web API  上

3,Azure AD(二)呼叫受Microsoft 標識平臺保護的 ASP.NET Core Web API 下

4,Azure AD(三)知識補充-Azure資源的託管標識

5,Azure AD(四)知識補充-服務主體

6,Azure AD(五)使用多租戶應用程式模式讓任何 Azure Active Directory 使用者登入

二,正文

1,修改受保護資源的應用的賬號型別

首先我們登陸Azure Portal 上,並且切換一下當前活動的目錄(也就是當前所在的租戶)

在之前在AAD中註冊好的應用註冊---”WebApi“,點選進入WebApi的設定

 點選圖中圈中的受支援的賬戶型別---僅我的組織

 修改 受支援的賬號型別 為 ”任何組合目錄(任何 Azure AD 目錄 - 都租戶)中的賬戶“,點選 ”儲存“

 

我們使用其他租戶的賬號登陸認證,提示  當前登陸賬號不在當前登陸的租戶內

2,修改程式碼配置

微軟官方文件給出,當使用多租戶模式的時候,

(1)程式碼需要更為為向/common 發出請求

  在單租戶應用程式中,登入請求將傳送到租戶的登入終結點。 以 trainingdiscussion.partner.onmschina.cn 為例,終結點將是:https://login.chinacloudapi.cn/trainingdiscussion.partner.onmschina.cn。 傳送到租戶終結點的請求可以讓該租戶中的使用者(或來賓)登入該租戶中的應用程式。

使用多租戶應用程式時,應用程式事先並不知道使用者來自哪個租戶,因此無法將請求傳送到租戶的終結點。 取而代之的是,請求將傳送到在所有 Azure AD 租戶之間多路複用的終結點:https://login.chinacloudapi.cn/common

  當 Microsoft 標識平臺在 /common 終結點上收到請求時,會使使用者登入,因而可以發現使用者來自哪個租戶。 /Common 終結點可與 Azure AD 支援的所有身份驗證協議配合使用: OpenID Connect、OAuth 2.0、SAML 2.0 和 WS 聯合身份驗證。

/common 終結點不是租戶,也不是頒發者,而只是一個多路複用器。 使用 /common 時,需要更新應用程式中用於驗證令牌的邏輯。然後,對應用程式做出的登入響應會包含代表該使用者的令牌。 令牌中的頒發者值告知應用程式該使用者來自哪個租戶。 從 /common 終結點返回響應時,令牌中的頒發者值將與使用者的租戶相對應。

(2)將程式碼更新為處理多個頒發者值

單租戶應用程式通常採用類似於下面的終結點值:https://login.chinacloudapi.cn/trainingdiscussion.partner.onmschina.cn

並使用該值構造元資料 URL(在本例中為 OpenID Connect),例如:https://login.chinacloudapi.cn/trainingdiscussion.partner.onmschina.cn/.well-known/openid-configuration

以下載用於驗證令牌的兩項關鍵資訊:租戶的簽名金鑰和頒發者值。 每個 Azure AD 租戶使用以下格式的唯一頒發者值:https://sts.chinacloudapi.cn/53359126-8bcf-455d-a934-5fe72d349207/

下圖中,是我當前AAD 租戶中註冊的 Web Api  的OpenID Connect 元資料文件

Authentication 配置

services.AddAuthentication("Bearer")
                .AddJwtBearer(o =>
                {
                    o.Audience = Appsettings.app(new string[] { "AzureAD", "ClientId" });
                    o.RequireHttpsMetadata = false;
                    o.SaveToken = true;
                    o.Authority = Appsettings.app(new string[] { "AzureAD", "Authority" });
                    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Appsettings.app(new string[] { "AzureAD", "Issuer" }),
                        ValidateLifetime = true,
                    };
                });

Swagger服務的配置

 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授權(資料將在請求頭中進行傳輸) 直接在下框中輸入Bearer {token}(注意兩者之間是一個空格)\"",
                    Type = SecuritySchemeType.OAuth2,
                    In = ParameterLocation.Header,//jwt預設存放Authorization資訊的位置(請求頭中)
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            //AuthorizationUrl = new Uri($"https://login.chinacloudapi.cn/{ Appsettings.app(new string[] { "AzureAD", "TenantId" })}/oauth2/authorize")
                            AuthorizationUrl = new Uri($"https://login.chinacloudapi.cn/common/oauth2/authorize")
                        }
                    }
                });
                // 在header中新增token,傳遞到後臺
                c.OperationFilter<SecurityRequirementsOperationFilter>();
            });

開啟中介軟體

#region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //根據版本名稱倒序 遍歷展示
                var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"{ApiName} v1");

                c.OAuthClientId(Appsettings.app(new string[] { "Swagger", "ClientId" }));
                //c.OAuthClientSecret(Appsettings.app(new string[] { "Swagger", "ClientSecret" }));
                c.OAuthRealm(Appsettings.app(new string[] { "AzureAD", "ClientId" }));
                c.OAuthAppName("My API V1");
                c.OAuthScopeSeparator(" ");
                c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { { "resource", Appsettings.app(new string[] { "AzureAD", "ClientId" }) } });
            });
            #endregion
            IdentityModelEventSource.ShowPII = true; // here
            app.UseAuthentication();

完整程式碼:

public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }

        public IWebHostEnvironment Environment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Appsettings(Environment.ContentRootPath));


            //services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
            //    .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

            services.AddAuthentication("Bearer")
                .AddJwtBearer(o =>
                {
                    o.Audience = Appsettings.app(new string[] { "AzureAD", "ClientId" });
                    o.RequireHttpsMetadata = false;
                    o.SaveToken = true;
                    o.Authority = Appsettings.app(new string[] { "AzureAD", "Authority" });
                    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = false,
                        ValidIssuer = Appsettings.app(new string[] { "AzureAD", "Issuer" }),
                        ValidateLifetime = true,

                    };
                });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授權(資料將在請求頭中進行傳輸) 直接在下框中輸入Bearer {token}(注意兩者之間是一個空格)\"",
                    Type = SecuritySchemeType.OAuth2,
                    In = ParameterLocation.Header,//jwt預設存放Authorization資訊的位置(請求頭中)
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            //AuthorizationUrl = new Uri($"https://login.chinacloudapi.cn/{ Appsettings.app(new string[] { "AzureAD", "TenantId" })}/oauth2/authorize")
                            AuthorizationUrl = new Uri($"https://login.chinacloudapi.cn/common/oauth2/authorize")
                        }
                    }
                });
                // 在header中新增token,傳遞到後臺
                c.OperationFilter<SecurityRequirementsOperationFilter>();
            });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //根據版本名稱倒序 遍歷展示
                var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"{ApiName} v1");

                c.OAuthClientId(Appsettings.app(new string[] { "Swagger", "ClientId" }));
                //c.OAuthClientSecret(Appsettings.app(new string[] { "Swagger", "ClientSecret" }));
                c.OAuthRealm(Appsettings.app(new string[] { "AzureAD", "ClientId" }));
                c.OAuthAppName("My API V1");
                c.OAuthScopeSeparator(" ");
                c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>() { { "resource", Appsettings.app(new string[] { "AzureAD", "ClientId" }) } });
            });
            #endregion
            IdentityModelEventSource.ShowPII = true; // here
            app.UseAuthentication();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
Startup
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AzureAd": {
      "Instance": "https://login.chinacloudapi.cn/common",
      "Domain": "trainingdiscussion.partner.onmschina.cn",
      "TenantId": "common",
      "ClientId": "f38ec09d-203e-4b2d-a1c1-faf76a608528",
"CallbackPath": "/signin-oidc",
    "Authority": "https://login.chinacloudapi.cn/organizations/v2.0/",
    "Issuer": "https://sts.chinacloudapi.cn/53359126-8bcf-455d-a934-5fe72d349207/"
    },
    "Swagger": {
      "ClientId": "62ca9f31-585c-4d28-84b6-25fb7855aed0",
      "ClientSecret": "" //  ?fxV/=/pwlRjwQgoIdLRlPNlWBBQ8939
    }
}
application

3,執行專案,進行測試

 我們進行測試 order 介面,提示 返回碼 401,無許可權。

我們點選頁面上的 ”Authorize“ 進行驗證

 這裡,我們輸入其他azure租戶的使用者的賬號資訊進行登陸驗證(因為這號牽扯個人隱私,所以目前不展示),點選下一步

 輸入 賬號密碼資訊,點選登陸

 登陸驗證通過後,我們再次進行驗證操作

 我們再次進行測試,ok,成功