IdentityServer簡介(摘自Identity官網)html
IdentityServer是將符合規範的OpenID Connect和OAuth 2.0端點添加到任意ASP.NET核心應用程序的中間件,一般,您構建(或從新使用)一個包含登陸和註銷頁面的應用程序(可能還包括贊成,具體取決於您的須要),IdentityServer中間件向其添加必要的協議頭,以便客戶端應用程序可使用這些標準協議與之對話。web
託管應用程序能夠像您但願的那樣複雜,但咱們一般建議經過只包含與身份驗證相關的UI來儘量地保持攻擊面小。api
client :客戶端,從identityServer請求令牌,用戶對用戶身份校驗,客戶端必須先從identityServer中註冊,而後才能請求令牌。瀏覽器
sources :每一個資源都有本身惟一的名稱,就是文中所定義的api1服務名稱,indentity會驗證斷定是否有訪問該資源的權限。服務器
access Token :訪問令牌,由identityServer服務器簽發的,客戶端使用該令牌進行訪問擁有權限的apiapp
OAuth 2.0四種受權模式(GrantType)ide
做用微服務
在多個應用程序當中進行統一登陸或者註銷。post
支持外部身份提供商,如Azure Active Directory、Google、Facebook等。這將使您的應用程序不瞭解如何鏈接到這些外部提供商的詳細信息。網站
開發準備
開發環境 :vs2019
identityServer4:2.4.0
netcore版本 :2.1
客戶端受權模式介紹
客戶端模式的話是屬於identityServer保護API的最基礎的方案,咱們定義個indentityServer服務以及一個須要保護的API服務,
當客戶端直接訪問api的話,因爲咱們的api服務添加了authorization認證,因此必需要到identityServer放服務器上拿到訪問令牌,客戶端憑藉該令牌去對應api服務當中獲取想要獲得的數據。
添加IdentityServer項目
1.首先添加新項目,建立ASP.NET Core Web 應用程序 建立一個名稱爲identityServer4test的項目,選擇項目類型API 項目進行建立。
2.從程序包管理器控制檯或者ngGet下載IdentityServer4
2.1 程序包管理器控制檯:install-package IdentityServer4
2.2 NuGet 的話在對應的程序集,選擇nuget輸入IdentityServer4選擇對應的版本進行下載安裝
3.添加Identity Server4 配置
資源定義能夠經過多種方式實現,具體的請查閱官方api文檔:https://identityserver4.readthedocs.io/en/latest/quickstarts/1_client_credentials.html
注:1.ApiResource("api1","My Api"),其中api1表明你的惟一資源名稱,在 AllowedScopes = { "api1" }當中必須配置上才能夠進行訪問
using IdentityServer4.Models; using IdentityServer4.Test; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4Test.IndntityConfig { public class IdentityServerConfig { /// <summary> /// 添加api資源 /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetResources() { return new List<ApiResource> {
new ApiResource("api1","My Api") }; } /// <summary> /// 添加客戶端,定義一個能夠訪問此api的客戶端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { /// ClientId = "client", // 沒有交互性用戶,使用 客戶端模式 進行身份驗證。 AllowedGrantTypes = GrantTypes.ClientCredentials, // 用於認證的密碼 ClientSecrets = { new Secret("123454".Sha256()) }, // 客戶端有權訪問的範圍(Scopes) AllowedScopes = { "api1" } } }; } } }
4.在startUp當中注入IdentityServer4 服務
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer4.Models; using IdentityServer4.Test; using IdentityServer4Test.IndntityConfig; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace IdentityServer4Test { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // 在DI容器中注入identityServer服務 services.AddIdentityServer() .AddInMemoryApiResources(IdentityServerConfig.GetResources())//添加配置的api資源 .AddInMemoryClients(IdentityServerConfig.GetClients())//添加客戶端,定義一個能夠訪問此api的客戶端 .AddDeveloperSigningCredential(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加identityserver中間件到http管道 app.UseIdentityServer(); //app.UseMvc(); } } }
5.此時啓動程序輸入 http://localhost:3322/.well-known/openid-configuration能夠獲得以下網站,這是identity Server4 提供的配置文檔
6.用postMan請求獲取access_token
標註:body 當中的參數
grant_type :對應api AllowedGrantTypes 類型表示受權模式
client_id : 對應clentID
client_secret: 客戶端祕鑰
7.拿到token之後就能夠根據token去訪問咱們的服務程序,服務程序,首先也是建立一個webApi程序,而且從NuGet下載所需的依賴
7.1 配置authentication,而且添加 app.UseAuthentication();到http管道當中
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace IndentityServerClientTest { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //注入authentication服務 services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://localhost:3322";//IdentityServer服務地址 options.ApiName = "api1"; //服務的名稱,對應Identity Server當中的Api資源名稱,若是客戶端獲得的token能夠訪問此api的權限才能夠訪問,不然會報401錯誤 options.RequireHttpsMetadata = false; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加authentication中間件到http管道 app.UseAuthentication(); app.UseMvc(); } } }
7.2 引用Microsoft.AspNetCore.Authorization;命名空間,添加authorize認證
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace IndentityServerClientTest.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } // DELETE api/values/5 [Route("send")] [HttpGet] public string send() { return "成功了"; } } }
7.3. 直接訪問的話會報401錯誤
7.4 在請求頭當中添加Authorization 參數,參數值爲Bearer加上空格 加上我們剛纔獲取到的access_token 請求成功!~~
密碼受權
官方介紹
OAuth2.0資源全部者密碼受權容許客戶端向令牌服務發送用戶名和密碼,並獲取表明該用戶的訪問令牌。
除了不能承載瀏覽器的遺留應用程序以外,規範一般建議不要使用資源全部者密碼授予。通常來講,當您想要對用戶進行身份驗證並請求訪問令牌時,最好使用交互式OpenID鏈接流之一。
然而,這種受權類型容許咱們將用戶的概念引入到QuickStartIdentityServer,這就是咱們展現它的緣由。
1.配置可訪問的用戶信息以及受權模式
新添加一個client模式而且更改AllowedGrantTypes 類型爲「GrantTypes.ResourceOwnerPassword」
using IdentityServer4.Models; using IdentityServer4.Test; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4Test.IndntityConfig { public class IdentityServerConfig { /// <summary> /// 添加api資源 /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetResources() { return new List<ApiResource> { new ApiResource("api1","My Api") }; } /// <summary> /// 添加客戶端,定義一個能夠訪問此api的客戶端 /// </summary> /// <returns></returns> public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { /// ClientId = "client", // 沒有交互性用戶,使用 客戶端模式 進行身份驗證。 AllowedGrantTypes = GrantTypes.ClientCredentials, // 用於認證的密碼 ClientSecrets = { new Secret("123454".Sha256()) }, // 客戶端有權訪問的範圍(Scopes) AllowedScopes = { "api1" } } , new Client { ClientId = "client1", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, // 用於認證的密碼 ClientSecrets = { new Secret("laozheng".Sha256()) }, RequireClientSecret=false, // 客戶端有權訪問的範圍(Scopes) AllowedScopes = { "api1" } } }; } public static List<TestUser> GetTestUsers() { return new List<TestUser> { new TestUser{ SubjectId="1", Password="111", Username="111", } }; } } }
1.1 修改startup.cs文件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer4.Models; using IdentityServer4.Test; using IdentityServer4Test.IndntityConfig; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace IdentityServer4Test { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // 在DI容器中注入identityServer服務 services.AddIdentityServer() .AddInMemoryApiResources(IdentityServerConfig.GetResources()) .AddInMemoryClients(IdentityServerConfig.GetClients()) .AddTestUsers(IdentityServerConfig.GetTestUsers()) .AddDeveloperSigningCredential(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //添加identityserver中間件到http管道 app.UseIdentityServer(); //app.UseMvc(); } } }
2.獲取token
3.經過剛纔獲取到的token訪問接口
快速入口:微服務(入門一):netcore安裝部署consul
快速入口: 微服務(入門二):netcore經過consul註冊服務