1 在 api 資源客戶端 使用 AddIdentityServerAuthentication 兼容 jwt和referencetoken(短token) 授權代碼如下:
在 Startup.cs 中ConfigureServices 方法使用如下代碼:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = Config.IdentityServerUri; // id4 server 地址 options.ApiName = Config.ApiName; // api 名 options.ApiSecret = Config.ApiSecret; // 配置的 api 秘鑰 使用 references token 要用到 options.RequireHttpsMetadata = false; // 不需要 https });
2 在 api 資源客戶端 使用 AddAuthentication 和 AddJwtBearer 兼容 jwt和referencetoken(短token) 授權代碼如下:
在 Startup.cs 中ConfigureServices 方法使用如下代碼:
// nuget 安裝 Microsoft.AspNetCore.Authentication.JwtBearer // jwt tokens services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme) .AddJwtBearer("Bearer", options => { options.Authority = Config.IdentityServerUri; // 設置 https options.RequireHttpsMetadata = true; options.Audience = Config.ApiName; // 支持 jwt 和 reference 兩種 token // if token does not contain a dot, it is a reference token options.ForwardDefaultSelector = context => "Introspection"; }); // reference tokens services.AddAuthentication("Introspection") .AddOAuth2Introspection("Introspection", options => { options.Authority = Config.IdentityServerUri; // this maps to the API resource name and secret options.ClientId = Config.ApiName; // api 名 options.ClientSecret = Config.ApiSecret; // 配置的 api 秘鑰 });
3 jwt token 和 reference token 區別
jwt token
在資源端(API)就可以完成驗簽的過程,不需要每次再去資源端驗簽以減少網絡請求,缺點就是生成的 Token 會很長,另外 Token 是不可撤銷的,Token 的生命周期(被驗證通過)會一直到票據過期,如果泄露就會比較麻煩
reference token
當使用 Reference token 的時候,服務端會對 Token 進行持久化,當客戶端請求資源端(API)的時候,資源端需要每次都去服務端通信去驗證 Token 的合法性[/connect/introspect],IdentityServer4.AccessTokenValidation 中間件中可以配置緩存一定的時候去驗證,並且 Token 是支持撤銷[/connect/revocation]的
參考鏈接
關於 IdentityServer4 中的 Jwt Token 與 Reference Token
https://cloud.tencent.com/developer/article/1644831