天天看點

IdentityServer4 關于 AddIdentityServerAuthentication 方法

AddIdentityServerAuthentication

是 IdentityServer 官方封裝的用于認證的方法,接入 ASP.NET Core 的認證機制,包含在元件

IdentityServer4.AccessTokenValidation

中。

在 ASP.NET Core 早期,1.1、2.0(2.0不确定,時間太久了)時 AddIdentityServerAuthentication 還是 IdentityServer 官方文檔及示例代碼提供的注冊認證的方法,後面都變更為了:

services.AddAuthentication("Bearer")
                .AddJwtBearer()
           

一度我曾經以為

AddIdentityServerAuthentication

無用了,現在我更正我的想法,這個方法同時支援了 Reference Token 和 JWT 的認證,是以說如果使用 Reference Token 還是要使用這個方法的。

當然,如果使用 JWT 的話還是推薦直接使用 AddJwtBearer ,這是微軟官方提供的支援JWT的認證元件,不用額外安裝 Nuget 包。

2020.10.15 再次更新

IdentityServer4.AccessTokenValidation 元件的 github 倉庫已經存檔了,然後我查詢了官方文檔,已經不使用這個元件了,對于 Reference Token 的驗證,使用 https://github.com/IdentityModel/IdentityModel.AspNetCore.OAuth2Introspection

如果同時支援 JWT 和 Reference Token ,那麼這樣寫:

services.AddAuthentication("token")

    // JWT tokens
    .AddJwtBearer("token", options =>
    {
        options.Authority = Constants.Authority;
        options.Audience = "resource1";

        options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };

        // if token does not contain a dot, it is a reference token
        options.ForwardDefaultSelector = Selector.ForwardReferenceToken("introspection");
    })

    // reference tokens
    .AddOAuth2Introspection("introspection", options =>
    {
        options.Authority = Constants.Authority;

        options.ClientId = "resource1";
        options.ClientSecret = "secret";
    });
           

相關資料:

https://docs.identityserver.io/en/latest/topics/apis.html

https://docs.identityserver.io/en/latest/topics/reference_tokens.html

目前學習.NET Core 最好的教程 .NET Core 官方教程 ASP.NET Core 官方教程

.NET Core 交流群:923036995  歡迎加群交流

如果您認為這篇文章還不錯或者有所收獲,您可以點選右下角的【推薦】支援,或請我喝杯咖啡【贊賞】,這将是我繼續寫作,分享的最大動力!

作者:曉晨Master(李志強)

聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格位址,如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!