.NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据

.NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据

内容:本文带大家使用IdentityServer4进行对API授权保护的基本策略

作者:zara(张子浩) 欢迎分享,但需在文章鲜明处留下原文地址。

  本文将要讲述如何使用IdentityServer4对API授权保护以及如何携带Token进行访问受保护的API,通过HttpClient或Http请求中的body这些我们都可以达到。那么废话不多说,开始吧~

  首先我们一定要知道,我们访问要访问一个受安全限制的API的锁子是在一个专门的IdentityServer4验证服务器。所以呢,我们需要创建一个认证服务器。首先我们创建一个API项目。

.NET Core IdentityServer4实战 第一章-入门与API添加客户端凭据

创建完成之后,我们再创建一个Config.cs,当然这个名字你随意,但你需要在DI注入的时候与其对应。在 GetSoluction 中定义了我们的API,也就是受保护的锁子,第一个参数是name,也就是Api的名称,那么后面是显示的名字,也就是DisplayName。在 GetClients 当中我们定义了受信任的客户端,其中有客户端的ID,授权方式,客户端加密方式,通过 AllowedScopes  还定义了这个客户端可以访问的API。

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"} } }; } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyjxwx.html