2. 使用IdentityServer4 實現 OAuth2 ClientCredential 模式

概述

  • OAuth2 的幾種角色和4中授權模式此處不再贅述,可以查看大神的文章 http://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html
  • 本例將實現最簡單的ClientCerdential 客戶端認證模式,該模式適合內部API使用。
  • 在將來的生產環境中,關於證書和持久化數據功能將在後續案例中實現。

環境

  • AspNetCore3.1

步驟

1. 新建一個AuthServer項目

使用AspNetCore 框架新建一個WebAPI項目,命名AuthServer,將此項目作爲Token認證授權中心。
添加nuget包:

        <PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.1" />

爲簡單起見,將此服務端口綁定到5010,表明我們認證授權中心的url 地址是 http://localhost:5010

      // 修改launchsettings.json
    "AuthServer": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "http://localhost:5010",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
1.1 創建資源
   // 一個靜態類,用於提取資源和客戶端相關的配置
    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources
            => new List<ApiResource> { new ApiResource("api", "api1 desc.") { Scopes = { "api" } } };

        public static IEnumerable<Client> GetClients
            => new List<Client> {
                new Client {
                    ClientId="webapi",
                    ClientSecrets=new[] {new Secret("123456".Sha256()) },
                    AllowedGrantTypes=GrantTypes.ClientCredentials,
                    ClientName="console",
                    AllowedScopes={ new ApiScope("api").Name }
            } };


        public static IEnumerable<ApiScope> GetApiScopes
            => new[] { new ApiScope("api")};
    }

需要注意的是在AspNetCore 3.1 使用IdentityService4 的4.x版本時,需要單獨定義ApiScope,並且client 的allowscopes 需要和ApiScope 的name一致,否則客戶端將無法找到scope。這個設計將scope 和ApiResource 進一步解耦了,關係會更加靈活。

1.2 註冊IdentityServer

在DI容器中註冊identityserver服務

        public static IServiceCollection AddOAuthClientCreditionPattern(this IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources)
                .AddInMemoryClients(Config.GetClients)
                .AddInMemoryApiScopes(Config.GetApiScopes) // 3.1 新增的坑,不加會報invalid_scope
                ;

            return services;

        }
       // Startup 中啓用
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOAuthClientCreditionPattern();
            services.AddControllers();
        }
       // 啓用中間件
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseIdentityServer();   // 啓用identityserver 中間件

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
     
1.3 啓用服務

至此AuthServer 創建成功
訪問 endpoint: 發現如下內容;IdentityServer4 已經定義了一系列uri 用於獲取token、userinfo等。
我將在後續示例中探討其他uri,本例要用到的是獲取token 的uri: http://localhost:5010/connect/token

{
	"issuer": "http://localhost:5010",
	"jwks_uri": "http://localhost:5010/.well-known/openid-configuration/jwks",
	"authorization_endpoint": "http://localhost:5010/connect/authorize",
	"token_endpoint": "http://localhost:5010/connect/token",
	"userinfo_endpoint": "http://localhost:5010/connect/userinfo",
	"end_session_endpoint": "http://localhost:5010/connect/endsession",
	"check_session_iframe": "http://localhost:5010/connect/checksession",
	"revocation_endpoint": "http://localhost:5010/connect/revocation",
	"introspection_endpoint": "http://localhost:5010/connect/introspect",
	"device_authorization_endpoint": "http://localhost:5010/connect/deviceauthorization",
	"frontchannel_logout_supported": true,
	"frontchannel_logout_session_supported": true,
	"backchannel_logout_supported": true,
	"backchannel_logout_session_supported": true,
	"scopes_supported": ["offline_access"],
	"claims_supported": [],
	"grant_types_supported": ["authorization_code", "client_credentials", "refresh_token", "implicit", "urn:ietf:params:oauth:grant-type:device_code"],
	"response_types_supported": ["code", "token", "id_token", "id_token token", "code id_token", "code token", "code id_token token"],
	"response_modes_supported": ["form_post", "query", "fragment"],
	"token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
	"id_token_signing_alg_values_supported": ["RS256"],
	"subject_types_supported": ["public"],
	"code_challenge_methods_supported": ["plain", "S256"],
	"request_parameter_supported": true
}

至此,authserver 認證授權中心創建OK。下面創建ApiResource,並使Api啓用基於的Token OAuth2認證.

1.4 獲取token

2. 創建WebApi

Api 客戶端使用Identityserver4 只需要nuget 引入一個 IdentityServer4.AccessTokenValidation 包即可。

 <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
2.1 新建一個AspNetCore WebApi 項目,將端口綁定到5020。
    "AuthTestApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "http://localhost:5020",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
2.2 Startup 註冊

註冊IdentityServer認證服務

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.ApiName = "api";
                    options.ApiSecret = "123456";
                    options.Authority = "http://localhost:5010";
                    options.RequireHttpsMetadata = false;

                });
            services.AddControllers();
        }
        
// 註冊中間件
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

注意的是: 中間件必須按先後順序啓用 app.UseAuthentication()、app.UseRouting()、app.UseAuthorization();

2.3 訪問api 資源
  • api 沒有添加過濾器時,可以正常訪問

  • 爲 接口添加上 Authorize 過濾器

 [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase

此時再訪問沒有token時,拒絕訪問,報401。

添加上文中拿到的token後訪問,成功!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章