.net core 3.1 Identity Server4 (ProfileService检测有效用户与获取Claims) 电脑版发表于:2021/2/20 14:39 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 3.1 Identity Server4 (ProfileService检测有效用户与获取Claims) [TOC] ![](https://img.tnblog.net/arcimg/hb/8e4abea9067d4157944d80e90497ace8.png) 目录 ------------ https://www.tnblog.net/hb/article/details/5458 关于IProfileService接口 ------------ tn>将用户所需的所有可能的声明放入cookie中是不切实际的,因此IdentityServer定义了一个扩展点(`IProfileService`),以允许根据用户的需要动态加载声明(`Claim`)。该接口通常会实现此接口来访问包含用户身份数据的自定义数据库或API。 Server中实现IProfileService ------------ tn>创建一个`ProfileService`类,实现`IProfileService`接口,具体如下代码所示。 ![](https://img.tnblog.net/arcimg/hb/d2ccc65d04294fa19dbed08cade1a786.png) ```csharp public class ProfileService : IProfileService { /// <summary> /// 获取用户的Claims /// </summary> /// <param name="context"></param> /// <returns></returns> public Task GetProfileDataAsync(ProfileDataRequestContext context) { // 添加claim context.IssuedClaims = new List<Claim> { new Claim("xType","xValue") }; return Task.CompletedTask; } /// <summary> /// identity server需要确定用户是否有效 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task IsActiveAsync(IsActiveContext context) { // 这里写你的逻辑,IsActive表示通过还是不通过,true表示通过 context.IsActive = true; return Task.CompletedTask; } } ``` tn>在`Startup`类中添加`.AddProfileService<ProfileService>()`方法 ![](https://img.tnblog.net/arcimg/hb/7f6156ba7a984a8eb80332fa27c2a1fe.png) 设置启动项 ------------ tn>这里我们启动 `HybridMvc` 客户端 ![](https://img.tnblog.net/arcimg/hb/55e811d0a00e4f048858f36c45a15f79.png) 添加映射 ------------ tn>在 `HybridMvc` 客户端的 `Startup` 中添加相关字段映射 ```csharp options.ClaimActions.MapUniqueJsonKey("xType", "xType"); ``` 运行测试 ------------ ![](https://img.tnblog.net/arcimg/hb/ca19ed06c4cf4f82830284508c036988.png) ![](https://img.tnblog.net/arcimg/hb/22fdcc54bfa54c7eac8023f69a91bb3d.png) ![](https://img.tnblog.net/arcimg/hb/7f34e36de462484caa491bd9a0d9e0de.png) ![](https://img.tnblog.net/arcimg/hb/072033fc25134dbaba737b0da67d2c08.png) ![](https://img.tnblog.net/arcimg/hb/8c0e90e9ad3148f8bd03ad249b9bae83.png) ![](https://img.tnblog.net/arcimg/hb/7d2d337b082b49fba15d18c18e9ec443.png)