内容:本文带你们使用IdentityServer4进行对API受权保护的基本策略api
做者:zara(张子浩) 欢迎分享,但需在文章鲜明处留下原文地址。浏览器
本文将要讲述如何使用IdentityServer4对API受权保护以及如何携带Token进行访问受保护的API,经过HttpClient或Http请求中的body这些咱们均可以达到。那么废话很少说,开始吧~安全
首先咱们必定要知道,咱们访问要访问一个受安全限制的API的锁子是在一个专门的IdentityServer4验证服务器。因此呢,咱们须要建立一个认证服务器。首先咱们建立一个API项目。服务器
建立完成以后,咱们再建立一个Config.cs,固然这个名字你随意,但你须要在DI注入的时候与其对应。在 GetSoluction 中定义了咱们的API,也就是受保护的锁子,第一个参数是name,也就是Api的名称,那么后面是显示的名字,也就是DisplayName。在 GetClients 当中咱们定义了受信任的客户端,其中有客户端的ID,受权方式,客户端加密方式,经过 AllowedScopes 还定义了这个客户端能够访问的API。app
using IdentityServer4.Models; using System.Collections.Generic; namespace IdentityServerSolution { /// <summary> /// zaranet 2019.1.26 14.10 create this file /// Config是IdentityServer的配置文件,一会咱们须要注册到DI层。 /// </summary> public class Config { /// <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"} } }; } } }
咱们如今已经写好了关于IdentityServer4服务器的配置文件,那么咱们还须要去依赖注入到.NET Core管道中,如今咱们看一下定义。ide
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddInMemoryApiResources(Config.GetSoluction()) .AddInMemoryClients(Config.GetClients()) .AddDeveloperSigningCredential(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //添加认证中间件 app.UseIdentityServer(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); }
就是这样 - 若是您运行服务器并浏览浏览器 http://localhost:您的端口/.well-known/openid-configuration ,您应该会看到所谓的发现文档。客户端和API将使用它来下载必要的配置数据。工具
首次启动时,IdentityServer将为您建立一个开发人员签名密钥,它是一个名为的文件tempkey.rsa
。您没必要将该文件检入源代码管理中,若是该文件不存在,将从新建立该文件。测试
如下是用PostMan进行的测试,以HttpPost方式进行请求,并在Http Body中进行编辑请求体上下文,测试结果以下。若是三个参数没有问题就返回token,若是其中三个参数有一个写错,那么就会返回400错误(error:invalid_client)。ui
下面在API项目中添加控制器:this
[Route("identity")] [Authorize] [ApiController] public class IdentityController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } }
稍后将使用此控制器来测试受权要求,以及经过API的眼睛可视化声明身份。如今咱们将身份验证服务添加到DI和身份验证中间价到管道中,验证传入令牌以确保它来自受信任的颁发者。
将Startup更新为以下所示:
public void ConfigureServices(IServiceCollection services) { services.AddMvcCore() .AddAuthorization() .AddJsonFormatters(); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "http://localhost:58653"; options.RequireHttpsMetadata = false; options.Audience = "api1"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); }
AddAuthentication 是为了用于将IdentityServer4访问令牌验证处理程序将在DI中提供身份验证服务。 UseAuthentication 将身份验证中间件添加到管道中,以便在每次调用主机时自动执行身份验证。若是你如今转到 http://localhost:prot/identity
中是401错误的话,说明API已经获得了保护。配置成功了!,如今咱们要建立咱们的客户端了。去访问受保护的API须要携带钥匙,那么这个钥匙术语叫作令牌,那就是通往大门的令牌!如今马上建立一个控制台程序,使用令牌访问API。
首先咱们须要安装IdentityModel,由于它能够替咱们找到元数据。
IdentityModel包括用于发现端点的客户端库。这样您只须要知道IdentityServer的基地址 - 能够从元数据中读取实际的端点地址:
var client = new HttpClient(); var disco = await client.GetDiscoveryDocumentAsync("http://localhost:58653"); if (disco.IsError) { Console.WriteLine(disco.Error); return; }
接下来,您能够使用发现文档中的信息来请求令牌:
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "Client", //id ClientSecret = "secret", //pwd Scope = "api1" //请求的api }); if (tokenResponse.IsError) { Console.WriteLine(tokenResponse.Error); return; }
要将访问令牌发送到API,一般使用HTTP Authorization标头。这是使用 SetBearerToken 扩展方法完成的:
var Apiclient = new HttpClient(); Apiclient.SetBearerToken(tokenResponse.AccessToken); var response = await client.GetAsync("http://localhost:58653/identity"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(JArray.Parse(content)); }
就这样,咱们启动结果以下,启动顺序,应先启动身份认证平台,而后再启动API,在启动控制台调试工具。
就这样一个简单的IdentityServer4身份认证平台就OK了,如今是否是想要迫切的试一下呢?哈哈,关于源代码,我放到个人Coding中了,地址是:https://coding.net/u/zaranet/p/IdentitySERVER,固然不要看着简单,仍是本身敲一下吧,若是你一点都没有碰过IdentityServer的话。下面咱们在回顾一下。
咱们在 IdentityServerSoluction 中定义了 Config 文件,用于Id4的配置,主要功能是为了认证模型,其中还设置了Client请求文中的 ClientId 这些参数等等。那么 IdentItyAPI 就是咱们的项目服务,其中经过 Authorize 标记的都是具备安全保护的API控制器,那么咱们就须要去获取咱们的IdentityServerSoluction 中的验证,这样咱们才能够访问,那么咱们就用了.NET Core控制台程序去模拟了这个过程,其中涉及了 HttpClient 相关知识。那么最后返回了咱们的相关 token ,这样,咱们能够根据 token 去获取咱们想要的API服务了!
最后祝你们春运快乐。下一篇干货在等你们噢!