敘述
最近在搞 IdentityServer4 API接口認證部分,由於之前沒有接觸過 IdentityServer4 於是在網上一頓搜搜搜,由於自己技術水平也有限,看了好幾篇文章才搞懂,想通過博客方式整理一下同時也希望幫到剛瞭解 IdentityServer4 的小夥伴。
在搭建 IdentityServer4 之前,需要了解以下幾個概念。
OpenId
OpenID 是一個以用戶爲中心的數字身份識別框架,它具有開放、分散性。OpenID 的創建基於這樣一個概念:我們可以通過 URI (又叫 URL 或網站地址)來認證一個網站的唯一身份,同理,我們也可以通過這種方式來作爲用戶的身份認證。
簡而言之:OpenId用於身份認證(Authentication)。
OAuth 2.0
OAuth(開放授權)是一個開放標準,目前的版本是2.0。允許用戶授權第三方移動應用訪問他們存儲在其他服務商上存儲的私密的資源(如照片,視頻,聯繫人列表),而無需將用戶名和密碼提供給第三方應用。
OAuth允許用戶提供一個令牌而不是用戶名和密碼來訪問他們存放在特定服務商上的數據。每一個令牌授權一個特定的網站內訪問特定的資源(例如僅僅是某一相冊中的視頻)。這樣,OAuth可以允許用戶授權第三方網站訪問他們存儲在另外服務提供者的某些特定信息,而非所有內容。
OAuth是OpenID的一個補充,但是完全不同的服務。
簡而言之:OAuth2.0 用於授權(Authorization)。
OpenId Connect
OpenID Connect 1.0 是基於OAuth 2.0協議之上的簡單身份層,它允許客戶端根據授權服務器的認證結果最終確認終端用戶的身份,以及獲取基本的用戶信息;它支持包括Web、移動、JavaScript在內的所有客戶端類型去請求和接收終端用戶信息和身份認證會話信息;它是可擴展的協議,允許你使用某些可選功能,如身份數據加密、OpenID提供商發現、會話管理等。
簡而言之:OpenId Connect = OIDC = Authentication + Authorization + OAuth2.0。
開始搭建 IdentityServer4
1.首先我們需要創建一個API項目來搭建 IdentityServer4 認證服務器。
2.通過 Nuget 安裝 IdentityServer4 。
3.刪除 .net core webapi 自帶的 WeatherForecast 控制器和 WeatherForecast 類。(當然不是必須刪除)
4.創建 ApiConfig 類用於配置 IdentityServer4 的參數。
using IdentityServer4.Models; using System.Collections.Generic; namespace IdentityServer { public class ApiConfig { /// <summary> /// 這個ApiResource參數就是我們Api /// </summary> /// <returns></returns> public static IEnumerable<ApiResource> GetSoluction() { return new[] { new ApiResource("api1", "MY API") }; } public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { ClientId = "Client", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("secret".Sha256()), }, AllowedScopes = {"api1"} } }; } } }
5.在 Startup.cs 中注入 IdentityServer 服務並使用中間件。
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddInMemoryApiResources(ApiConfig.GetSoluction()) .AddInMemoryClients(ApiConfig.GetClients()) .AddDeveloperSigningCredential(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //添加認證中間件 app.UseIdentityServer(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
6. F5運行項目,並將路徑修改爲: http://localhost:55320/.well-known/openid-configuration
首次啓動時,IdentityServer將爲您創建一個開發人員簽名密鑰,它是一個名爲的文件tempkey.rsa
。您不必將該文件檢入源代碼管理中,如果該文件不存在,將重新創建該文件。
7.用 Postman 測試並獲取 AccessToken,如下圖所示,在 Post 請求中傳入,認證類型,client_id 以及 client_secret 即可獲取 AccessToken 。
8.創建個 API 項目用於驗證 IdentityServer4 。
9.添加名爲 Identity 的控制器。
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace Api.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class IdentityController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } } }
10.通過 NuGet 安裝 IdentityServer4.AccessTokenValidation 。
11. 在 Startup.cs 中加入 identityServer 驗證。
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvcCore() .AddAuthorization(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://localhost:55320"; options.RequireHttpsMetadata = false; options.ApiName = "api1"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // 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.UseRouting(); app.UseAuthentication(); //認證服務 app.UseAuthorization(); //使用授權服務 app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
12.同時啓動 Api 項目和 Identity 驗證服務器。
13.使用 PostMan 進行驗證。
源碼:
鏈接: https://pan.baidu.com/s/17ZZqWZi4nCDKEO4o7dLafA
提取碼: t8hb
總結:
本文只是初步搭建 IdentityServer4 驗證服務器,並沒有更深入的探索,如果想有更深入瞭解的小夥伴可以參考以下鏈接。
參考:
https://www.cnblogs.com/sheng-jie/p/9430920.html
https://www.cnblogs.com/yilezhu/p/9315644.html
https://www.cnblogs.com/ZaraNet/p/10323400.html
https://www.cnblogs.com/lihuadeblog/p/12123686.html