IdentityServer4 4.x版本 配置Scope的正確姿勢

来源:https://www.cnblogs.com/xhznl/archive/2020/07/03/13223964.html
-Advertisement-
Play Games

前言 IdentityServer4 是為ASP.NET Core系列量身打造的一款基於 OpenID Connect 和 OAuth 2.0 認證的框架 IdentityServer4官方文檔:https://identityserver4.readthedocs.io/ 看這篇文章前預設你對Id ...


前言

IdentityServer4 是為ASP.NET Core系列量身打造的一款基於 OpenID Connect 和 OAuth 2.0 認證的框架

IdentityServer4官方文檔:https://identityserver4.readthedocs.io/

看這篇文章前預設你對IdentityServer4 已經有一些瞭解。

本篇使用IdentityServer4的4.x版本,跟老版本的稍微有些差別。下麵直接進入正題。

鑒權中心

創建IdentityServer4項目

使用IdentityServer4 來搭建一個鑒權中心,首先建議安裝一下IdentityServer4的官方項目模板。也可以不安裝,自己創建項目,然後NuGet安裝需要的包也行。(不過還是推薦用官方的模板,很方便)。

命令行執行:dotnet new -i IdentityServer4.Templates

image-20200629205619088

安裝完成後會多出以下項目模板:

image-20200629205731577

我這裡選用is4inmem這個模板來創建項目,這個模板的數據都是寫死在記憶體中的,並且包含了Quickstart頁面,比較簡單方便。

來到我的項目目錄下執行:dotnet new is4inmem --name Idp

image-20200701190325246

執行完成會生成以下文件:

image-20200701195853822

VS2019打開項目:

image-20200701195955107

運行項目:

image-20200701200225015

配置ApiResource、ApiScope、Clients

修改Startup:

// in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
//添加API資源
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);

這裡比之前版本多了一個添加ApiScopes的方法:

builder.AddInMemoryApiScopes(Config.ApiScopes);

因為我接下來有要保護的API資源,所以需要添加一行:

builder.AddInMemoryApiResources(Config.ApiResources);

Config中的代碼:

public static class Config
{
    public static IEnumerable<IdentityResource> IdentityResources =>
        new IdentityResource[]
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };

    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[]
        {
            new ApiScope("scope1"),
            //new ApiScope("scope2"),
        };

    public static IEnumerable<ApiResource> ApiResources =>
        new ApiResource[]
        {
            new ApiResource("api1","#api1")
            {
                //!!!重要
                Scopes = { "scope1"}
            },
            //new ApiResource("api2","#api2")
            //{
            //    //!!!重要
            //    Scopes = { "scope2"}
            //},
        };

    public static IEnumerable<Client> Clients =>
        new Client[]
        {
            new Client
            {
                ClientId = "postman client",
                ClientName = "Client Credentials Client",

                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets = { new Secret("postman secret".Sha256()) },

                AllowedScopes = { "scope1" }
            },
        };
}

我添加了一個ID為postman client的客戶端,授權模式就用最簡單的ClientCredentials客戶端模式。需要註意的是4.x版本的ApiScope和ApiResource是分開配置的,然後在ApiResource中一定要添加Scopes。如果你在網上搜的IdentityServer4教程比較老的,都是沒有這個ApiScope的,預設ApiResource的Name作為Scope。類似這樣:

public static IEnumerable<ApiResource> ApiResources =>
        new ApiResource[]
        {
            new ApiResource("api1","#api1"),//錯誤
            new ApiResource("api2","#api2"),//錯誤
        };


public static IEnumerable<Client> Clients =>
        new Client[]
        {
            new Client
            {
                ......

                AllowedScopes = { "api1", "api2" }
            },
        };

如果你這麼寫的話,雖然不影響你獲取token,但是你訪問api資源的話,永遠會得到一個401錯誤!!!
Audience validation failed. Audiences: 'xxx, http://xxx/resources'. Did not match: validationParameters.ValidAudience: 'xxx' or validationParameters.ValidAudiences: 'null'.

ApiResource

下麵添加一個api1資源,新建asp.netcore web應用並使用webapi模板:

image-20200701211036365

NuGet安裝:Microsoft.AspNetCore.Authentication.JwtBearer

Startup部分代碼:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            //IdentityServer地址
            options.Authority = "http://localhost:5001";
            //對應Idp中ApiResource的Name
            options.Audience = "api1";
            //不使用https
 		    options.RequireHttpsMetadata = false;
        });
}

// 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();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    //身份驗證
    app.UseAuthentication();

    //授權
    app.UseAuthorization();

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

給WeatherForecastController添加[Authorize]標記:

image-20200701214601854

運行Api1Resource,用postman測試訪問weatherforecast介面:

image-20200701214742071

此時得到401錯誤。下麵先去Idp獲取一個token:

image-20200701215031535

拿到token後再去訪問weatherforecast就沒問題了:

image-20200701215748634

進行到這裡,好像跟scope都沒什麼關係,那麼scope到底有什麼用處呢?

ApiScope策略授權

繼續修改代碼。

Api1Resource項目NuGet安裝:IdentityServer4.AccessTokenValidation

image-20200701221017612

再新建一個TestController用於區分:

image-20200701223359517

下麵我需要做的是使用scope結合策略授權來分別限制TestController和WeatherForecastController的訪問許可權。

修改Startup:

public void ConfigureServices(IServiceCollection services)
{
    ......

    services.AddAuthorization(options =>
    {
        //基於策略授權
        options.AddPolicy("WeatherPolicy", builder =>
        {
            //客戶端Scope中包含api1.weather.scope才能訪問
            builder.RequireScope("api1.weather.scope");
        });
        //基於策略授權
        options.AddPolicy("TestPolicy", builder =>
        {
            //客戶端Scope中包含api1.test.scope才能訪問
            builder.RequireScope("api1.test.scope");
        });
    });
}

為了好理解,我把scope名稱分別改成了:api1.weather.scope和api1.test.scope。

WeatherForecastController的Authorize標記修改一下:[Authorize(Policy = "WeatherPolicy")]

TestController的代碼很簡單:

image-20200701224046637

因為修改了scope名稱,需要把Idp中的scope名稱也改一下:

public static IEnumerable<ApiScope> ApiScopes =>
    new ApiScope[]
    {
        new ApiScope("api1.weather.scope"),
        new ApiScope("api1.test.scope"),
        //new ApiScope("scope2"),
    };

public static IEnumerable<ApiResource> ApiResources =>
    new ApiResource[]
    {
        new ApiResource("api1","#api1")
        {
            //!!!重要
            Scopes = { "api1.weather.scope", "api1.test.scope" }
        },
        //new ApiResource("api2","#api2")
        //{
        //    //!!!重要
        //    Scopes = { "scope2"}
        //},
    };

客戶端定義,AllowedScopes暫時只給一個api1.weather.scope測試一下

public static IEnumerable<Client> Clients =>
            new Client[]
            {
                new Client
                {
                    ClientId = "postman client",
                    ClientName = "Client Credentials Client",

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets = { new Secret("postman secret".Sha256()) },

                    AllowedScopes = { "api1.weather.scope" }
                },
            };

postman獲取token:

image-20200701225242813

訪問weatherforecast介面,正常響應200。

image-20200701225430395

再訪問test,得到403錯誤:

image-20200701225508071

接下來修改一下Idp的客戶端定義,添加api1.test.scope:

AllowedScopes = { "api1.weather.scope", "api1.test.scope" }

修改Idp後一定要重新獲取token,jwt就是這樣,一旦生成就無法改變。

image-20200701230022811

拿到新的token後訪問test和weatherforecast,這時候就都可以正常響應了。

image-20200701230107290

image-20200701230209695

總結

以上使用IdentityServer4搭建了一個鑒權中心,保護API資源,並使用ApiScope配合策略授權完成了一個簡單的許可權控制。IdentityServer4的玩法非常多,知識點也很多。強烈推薦B站的@solenovex 楊老師的視頻,地址:https://www.bilibili.com/video/BV16b411k7yM 多看幾遍,會有收穫。。。

需要代碼的點這裡:https://github.com/xiajingren/IdentityServer4-4.x-Scope-Demo


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • opencv——threshold閾值處理、自適應閾值處理、otsu處理(大津法) ...
  • 開胃菜 ——實現遍歷集合,開啟Stream流的便利化 import java.util.ArrayList; import java.util.Collections; public class Main{ public static void main(String[] args) { Array ...
  • hashCode介紹: hashCode()的作用是獲取哈希碼,它實際上是返回一個int整數。這個哈希碼的作用是確定該對象在哈希表中的索引位置。hashCode()定義在JDK的Object.java中,這就意味著Java中的任何類都包含有hashCode()函數。散列表存儲的是鍵值對(key-va ...
  • 今天介跟大家分享一下我平時閱讀源碼的幾個小技巧,對於閱讀java中間件如Spring、Dubbo等框架源碼的同學有一定幫助。 本文基於Eclipse IDE,我們每天都使用的IDE其實提供了很多強大的功能,掌握它們,往往能夠事半功倍。 1、Quick Type Hierarchy 快速查看類繼承體系 ...
  • 昵稱:(OrangeCsong)橘松(在其他平臺也是這個名字) 年齡:95後(摩羯座) 性別:boy 性格:性格還闊以,不輕易發脾氣,沉穩。喜歡獨立思考。 愛好:運動(工作了,運動時間太少),基金理財,很少玩游戲。 工作:杭漂程式🐶(後端開發) 坐標:杭州(江西銀,老表你來了) 公眾號:橘松Jav ...
  • C#中foreach的實現原理 在探討foreach如何內部如何實現這個問題之前,我們需要理解兩個C#裡邊的介面,IEnumerable 與 IEnumerator. 在C#裡邊的遍歷集合時用到的相關類中,IEnumerable是最基本的介面。這是一個可以進行泛型化的介面,比如說IEnumerabl ...
  • 使用博客園寫博客也有2年有餘了,對博客園是有一種莫名的親切感和深刻的感情的,這2多年來一直堅持寫著博客,也是對自己的一個很好的技術歷程總結。每次學習了一些新的技術,或者有一些感興趣的方向,都會通過隨筆進行記錄,有時候也會總結很多自己的開發成果,隨著技術路線的成熟,基本上是分享我的.NET相關技術。 ...
  • vs2019創建webapi 1.創建新的項目 2.選擇.NET CORE的ASP .NET CORE WEB應用程式 3.定義項目名稱和存放地點 4.選擇API創建項目 5.刪除原本的無用的類 6.添加新的方法類 7.設置路由 using Microsoft.AspNetCore.Componen ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...