從Client應用場景介紹IdentityServer4(一)

從Client應用場景介紹IdentityServer4(一)
原文:從Client應用場景介紹IdentityServer4(一)

一、背景

IdentityServer4的介紹將不再敘述,百度下可以找到,且官網的快速入門例子也有翻譯的版本。這里主要從Client應用場景方面介紹對IdentityServer4的應用。

首先簡要介紹ID Token和Access Token:

Access Token是授權第三方客戶端訪問受保護資源的令牌。 ID Token是第三方客戶端標識用戶身份認證的問令牌,是JSON Web Token格式。

?


?

二、Client應用場景介紹

Client類是為OpenID Connect或OAuth 2.0 協議建模的。

我們先看官網快速入門中給的Client例子

 public static IEnumerable<Client> GetClients(){// client credentials clientreturn new List<Client>{new Client{ClientId = "Client",AllowedGrantTypes = GrantTypes.ClientCredentials,ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes = { "api1" }},// resource owner password grant clientnew Client{ClientId = "ro.client",AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,ClientSecrets = {new Secret("secret".Sha256())},AllowedScopes = { "api1" }                },// OpenID Connect hybrid flow and client credentials client (MVC)new Client{ClientId = "mvc",ClientName = "MVC Client",AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,ClientSecrets ={new Secret("secret".Sha256())},RedirectUris = { "http://localhost:5002/signin-oidc" },PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },AllowedScopes ={IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,"api1"},AllowOfflineAccess = true},// JavaScript Clientnew Client{ClientId = "js",ClientName = "JavaScript Client",AllowedGrantTypes = GrantTypes.Implicit,AllowAccessTokensViaBrowser = true,RedirectUris = { "http://localhost:5003/callback.html" },PostLogoutRedirectUris = { "http://localhost:5003/index.html" },AllowedCorsOrigins = { "http://localhost:5003" },AllowedScopes ={IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,"api1"},}};}

里面主要介紹四種Client應用場景。

(1)客戶端模式(AllowedGrantTypes = GrantTypes.ClientCredentials)

? ? 這是一種最簡單的授權方式,應用于服務于服務之間的通信,token通常代表的是客戶端的請求,而不是用戶。

? ? 使用這種授權類型,會向token endpoint發送token請求,并獲得代表客戶機的access token。客戶端通常必須使用token endpoint的Client ID和secret進行身份驗證。

? ? 適用場景:用于和用戶無關,服務與服務之間直接交互訪問資源

(2)密碼模式(ClientAllowedGrantTypes = GrantTypes.ResourceOwnerPassword)

? ? 該方式發送用戶名和密碼到token endpoint,向資源服務器請求令牌。這是一種“非交互式”授權方法。

? ??官網上稱,為了解決一些歷史遺留的應用場景,所以保留了這種授權方式,但不建議使用。

? ? 適用場景:用于當前的APP是專門為服務端設計的情況。

(3)混合模式和客戶端模式(ClientAllowedGrantTypes =GrantTypes.HybridAndClientCredentials)

? ? ClientCredentials授權方式在第一種應用場景已經介紹了,這里主要介紹Hybrid授權方式。Hybrid是由Implicit和Authorization code結合起來的一種授權方式。其中Implicit用于身份認證,ID token被傳輸到瀏覽器并在瀏覽器進行驗證;而Authorization code使用反向通道檢索token和刷新token。

? ? 推薦適用Hybrid模式。

? ??適用場景:用于MVC框架,服務器端 Web 應用程序和原生桌面/移動應用程序。

(4)簡化模式(ClientAllowedGrantTypes =GrantTypes.Implicit)

? ? Implicit要么僅用于服務端和JavaScript應用程序端進行身份認證,要么用于身份身份驗證和access token的傳輸。

? ? 在Implicit中,所有token都通過瀏覽器傳輸的。

? ? 適用場景:JavaScript應用程序。


?

三、Server端搭建

為了介紹IdentityServer4的Client應用場景,我們需要先搭建IdentityServer服務端。

這里搭建的是使用EF Core來做數據操作,保存到SQL Server中。

(1)新建API項目

(2)安裝IdentityServer4.EntityFramework包

(3)安裝IdentityServer4包

(4)右鍵項目的屬性,編輯項目的.csproj文件

添加如下元素

<ItemGroup><DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

如圖:

(5)cmd管理員身份進入項目目錄路徑(D:\IdentityServer4\Server),運行:dotnet ef

(6)項目內添加Config.cs類,代碼如下

 public class Config{public static List<TestUser> GetUsers(){return new List<TestUser>{new TestUser{SubjectId = "1",Username = "alice",Password = "password",Claims = new List<Claim>(){new Claim(JwtClaimTypes.Role,"superadmin") }},new TestUser{SubjectId = "2",Username = "bob",Password = "password",Claims = new List<Claim>{new Claim("name", "Bob"),new Claim("website", "https://bob.com")},}};}public static IEnumerable<Client> GetClients(){// client credentials clientreturn new List<Client>{new Client{ClientId = "Client",AllowedGrantTypes = GrantTypes.ClientCredentials,ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes = { "api1" }},// resource owner password grant clientnew Client{ClientId = "ro.client",AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,ClientSecrets ={new Secret("secret".Sha256())},AllowedScopes = { "api1" }},// OpenID Connect hybrid flow and client credentials client (MVC)new Client{ClientId = "mvc",ClientName = "MVC Client",AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,ClientSecrets ={new Secret("secret".Sha256())},RedirectUris = { "http://localhost:5002/signin-oidc" },PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },AllowedScopes ={IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,"api1"},AllowOfflineAccess = true},// JavaScript Clientnew Client{ClientId = "js",ClientName = "JavaScript Client",AllowedGrantTypes = GrantTypes.Implicit,AllowAccessTokensViaBrowser = true,RedirectUris = { "http://localhost:5003/callback.html" },PostLogoutRedirectUris = { "http://localhost:5003/index.html" },AllowedCorsOrigins = { "http://localhost:5003" },AllowedScopes ={IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile,"api1"},}};}public static IEnumerable<IdentityResource> GetIdentityResources(){return new List<IdentityResource>{new IdentityResources.OpenId(),new IdentityResources.Profile(),};}public static IEnumerable<ApiResource> GetApiResources(){return new List<ApiResource>{new ApiResource("api1", "My API")};}

添加引用:

using IdentityModel;

using IdentityServer4;

using IdentityServer4.Models;

using IdentityServer4.Test;

using System.Collections.Generic;

using System.Security.Claims;

(7)編輯Startup.cs文件的ConfigureServices方法,改成如下代碼。

public void ConfigureServices(IServiceCollection services){const string connectionString = @"Server=localhost;database=IdentityServer4;User ID=sa;Password=Pwd;trusted_connection=yes";var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;// configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer().AddDeveloperSigningCredential().AddTestUsers(Config.GetUsers())// this adds the config data from DB (clients, resources).AddConfigurationStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));})// this adds the operational data from DB (codes, tokens, consents).AddOperationalStore(options =>{options.ConfigureDbContext = builder =>builder.UseSqlServer(connectionString,sql => sql.MigrationsAssembly(migrationsAssembly));// this enables automatic token cleanup. this is optional.options.EnableTokenCleanup = false;//是否從數據庫清楚令牌數據,默認為falseoptions.TokenCleanupInterval = 300;//令牌過期時間,默認為3600秒,一個小時
                });//.AddInMemoryClients(Config.GetClients());
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}

添加引用:

using Microsoft.EntityFrameworkCore;

using System.Reflection;

(8)cmd管理員身份進入到項目目錄路徑(D:\IdentityServer4\Server\Server),注意,多了一層目錄,分別運行以下兩條指令:

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDbdotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

運行完后,項目中會多了一個Data文件夾

(9)在Startup.cs中添加初始化數據庫方法。

private void InitializeDatabase(IApplicationBuilder app)
{using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()){serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();context.Database.Migrate();if (!context.Clients.Any()){foreach (var client in Config.GetClients()){context.Clients.Add(client.ToEntity());}context.SaveChanges();}if (!context.IdentityResources.Any()){foreach (var resource in Config.GetIdentityResources()){context.IdentityResources.Add(resource.ToEntity());}context.SaveChanges();}if (!context.ApiResources.Any()){foreach (var resource in Config.GetApiResources()){context.ApiResources.Add(resource.ToEntity());}context.SaveChanges();}}
}

添加引用:

using IdentityServer4.EntityFramework.DbContexts;

using IdentityServer4.EntityFramework.Mappers;

(10)在Startup.cs中的Configure方法修改成以下代碼。

  public void Configure(IApplicationBuilder app, IHostingEnvironment env){//if (env.IsDevelopment())//{//    app.UseDeveloperExceptionPage();//}
            InitializeDatabase(app);//app.UseMvc();}

到這里,把項目以控制臺形式運行

點擊運行,可以跑起來,且生成數據庫IdentityServer4DB。

關于Client的說明可以查閱官網資料:https://identityserver4.readthedocs.io/en/release/reference/client.html


?

源碼地址:https://github.com/Bingjian-Zhu/Server.git

服務端準備好之后,下篇文章開始介紹Client客戶端的應用。

文中如有錯漏,歡迎指正,將對此系列文章進行維護。

posted on 2018-12-26 22:30 NET未來之路 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/lonelyxmas/p/10182274.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/248764.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/248764.shtml
英文地址,請注明出處:http://en.pswp.cn/news/248764.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

開發常用代碼筆記

Vue 使用moment插件對時間進行格式化&#xff08;全局設置&#xff09; 下載插件 npm install moment --save 在main.js中引入插件 import moment from ‘moment’ 在main.js中定義全局過濾器 Vue.filter(dataFilter,function (dataStr,patten YYYY-MM-DD HH:mm:ss) {retur…

springboot 參數校驗詳解

https://www.jianshu.com/p/89a675b7c900 在日常開發寫rest接口時&#xff0c;接口參數校驗這一部分是必須的&#xff0c;但是如果全部用代碼去做&#xff0c;顯得十分麻煩&#xff0c;spring也提供了這部分功能,本文來探究一下如何實現 1.配置 spring-boot-starter-web包自動依…

微信小程序——賬號及開發工具

1. 注冊微信小程序賬號 點擊我進入微信公眾平臺 進入后點擊立即注冊 注冊成功且登錄后進入小程序管理后臺 2. 安裝開發者工具 點擊進入開發文檔 進入安裝開發工具&#xff08;穩定版本&#xff09; 一路默認下一步進行安裝 3. 開發者工具的使用 使用注冊微信小程序的微信號…

CSS注意的地方

content-box和border-box的區別 2018年02月27日 22:20:16 sulingliang 閱讀數&#xff1a;8011盒子模型 盒子寬度&#xff1a;paddingbordercontent-width 盒子高度&#xff1a;paddingbordercontent-height 如圖所示 盒子模型content-box 說明&#xff1a;在內容寬度和高度之…

機器學習筆記(6) 線性回歸

先從最簡單的例子開始,假設我們有一組樣本(如下圖的一個個黑色的圓點),只有一個特征,如下圖,橫軸是特征值,縱軸是label。比如橫軸是房屋面積,縱軸是房屋價格. 現在我們要做什么呢&#xff1f;我們試圖找到一條直線yaxb,可以盡量好的擬合這些點. 你可能要問了,為啥是直線,不是曲…

仿微信朋友圈項目梳理

項目功能簡介&#xff1a; 用戶通過手機號驗證碼進行登錄和注冊 可以瀏覽動態列表中的所有動態 登錄成功后用戶可以發表自己的動態 也可以對自己認可欣賞的動態進行點贊和評論 也可以通過動態結識志同道合的朋友 進行聊天和探討 前端&#xff1a;采用Vue框架搭建 weui進行頁面…

如何處理大流量高并發

1.動靜分離。 將網站中的靜態資源單獨拆分出來, 比如 css, js, 圖片, 視頻資源單獨存儲在一臺服務器上, 或者直接使用云存儲平臺, 七牛云或者阿里云之類的, 這樣能有效的降低主服務器的運行壓力 2.CDN加速。 云平臺提供 CDN 加速, 可以對資源進行全國服務器節點的分發, 提高全國…

echarts鼠標事件以及自定義數據獲取

事件添加方法&#xff1a; 對應官網位置&#xff1a;https://www.echartsjs.com/api.html#events 鼠標事件包括 click、dblclick、mousedown、mousemove、mouseup、mouseover、mouseout、globalout、contextmenu。 myChart.on(click, function (params) {console.log(params); …

[數學]點、線、面分割問題

平面分割問題 p條直線相交于一點時&#xff0c;分割的圖形有 2*(n-1) 個&#xff0c;此時再加一條直線&#xff0c;在 2*(n-1) 的基礎上再加 n條&#xff0c;此時為2*n n條曲線&#xff0c;其中有m條相交于一點&#xff0c;每兩個曲線都交于兩點 平面上有n條直線&#xff0c;且…

移動開發

1.移動端基礎 1.1 瀏覽器現狀 PC端瀏覽器 360瀏覽器、谷歌瀏覽器、火狐瀏覽器、QQ瀏覽器、百度瀏覽器&#xff08;停止服務&#xff09;、搜狗瀏覽器、IE瀏覽器 移動端瀏覽器 UC、QQ瀏覽器、歐朋瀏覽器、百度手機瀏覽器、360、搜狗、獵豹、谷歌等其他手機自帶的瀏覽器 國…

Django之路由系統

Django的路由系統 Django 1.11版本 URLConf官方文檔 URL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL與要為該URL調用的視圖函數之間的映射表。 你就是以這種方式告訴Django&#xff0c;對于這個URL調用這段代碼&#xff0c;對于那個URL調用那段代碼。 URLconf配置…

微信小程序——操作數據庫

案例一&#xff1a;統計用戶的訪問次數 業務需求&#xff1a; 統計每個用戶對程序的訪問次數將訪問次數存儲到數據庫中訪問次數應該與用戶進行關聯 業務邏輯&#xff1a; 如果用戶是第一次訪問此程序&#xff0c;向數據庫添加一條記錄&#xff1a;{openid&#xff1a;45454…

shop--12.阿里云部署以及域名綁定

一、申請阿里云服務器&#xff08;1&#xff09;PC訪問阿里云https://www.aliyun.com/&#xff0c;申請阿里云帳號&#xff08;可以用您的支付寶帳號登錄&#xff0c;因為支付寶帳號已經進行了實名認證&#xff0c;使用起來更方便&#xff09;并登錄&#xff08;2&#xff09;找…

微信小程序——獲取用戶的運動步數

程序獲取用戶信息步驟 點擊參考微信文檔中的授權首先程序先向用戶申請訪問哪些權限用戶做出選擇后返回給程序程序攜帶權限訪問服務器如果用戶允許則返回信息如果用戶為允許則不返回 自定義函數getUserRun 為獲取用戶的微信運動數據 頁面加載調用此函數函數中執行下面操作 1…

C++之前置自增與后置自增

關于前置自增與后置自增的區別我是參考這里&#xff1a;http://bbs.bccn.net/thread-454977-1-1.html 簡單復述下&#xff0c;比如x; 與 x; 在C中&#xff0c;x這個表達式的值為原先x的值1&#xff0c;副作用是x的值增加了1&#xff1b;&#xff08;C中不是這樣定義的&#xff…

第一次個人作業

該作業所屬課程&#xff1a;https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2作業要求地址&#xff1a;https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2/homework/3340團隊名稱&#xff1a;腦殼痛 作業的目標 1.通過測試其他組的軟件項目學習其…

微信小程序——解決上傳并部署云函數時報錯ResourceNotFound.Function, 未找到函數版本,請創建后再試。 (7f2d9d2d-5eac-4575-9n57-acd66cfa587g

1. 上傳部署我們的云函數 2. 報錯 錯誤信息為&#xff1a;Error: ResourceNotFound.Function, 未找到函數版本&#xff0c;請創建后再試。 (7f2d9d2d-5eac-4575-9b57-acd66cfa587e) 3. 原因 原因是可能我們在調試的時候不小心將我們開發控制臺中的云函數刪除了 4. 解決辦法…

前端面試題——HTML基礎篇

如何進行網站的性能優化 content方面 減少http請求 合并文件 css精靈圖減少 DNS 查詢 DNS緩存 將資源分布到恰當數量的主機名減少 DOM 元素的數量 Server方面 使用CDN配置Etag對組件使用 Gzip 壓縮 Cookie方面 減小cookie大小 css方面 將樣式表放到頁面頂部不使用css表…

【IT界的廚子】醬香鱸魚

食材: 前世曾經回眸的鱸魚一條(主要選刺少的魚&#xff0c;適合孩子吃&#xff0c;大人吃隨意&#xff0c;草魚比較大) 五花肉少許(肥一些的) 豆腐 輔料: 蔥姜 蒜(選) 大料 香菜 調味: 啤酒(兩罐) 黃豆醬或豆瓣醬(選) 老抽 生抽 料酒 鹽 步驟: 1、魚肉劃開&#xff0c;方便燉的…

第二章:09流程控制[3for]

①格式for(初始化語句;判斷條件語句;控制條件語句) { 循環體語句; } ②注意事項A:判斷條件語句無論簡單還是復雜結果是boolean類型。 B:循環體語句如果是一條語句,大括號可以省略&#xff1b;如果是多條語句,大括號不能省略。建議永遠不要省略。 C:一般來說&#xff1a;有左大括…