前言
在前几篇的学习中,生成的 Token 中只有 sub 这一个用户属性,其他的 username、email、phone等用户属性均没有包含在内。在实际项目中又常常需要从 token 中取得 用户的 sex、head 等属性,本篇笔者将介绍一种添加自定义用户属性的方法,供笔友参考。
IProfileService
ids 4里面定义了一个IProfileService的接口用来获取用户的一些信息, 主要是为当前的认证上下文绑定claims。我们可以实现IProfileService从外部创建claim扩展到ids4里面。
自定义 CustomerProfileService
在 MicroShell.IdentityServer4.Server 项目新建 CustomerProfileService 类,实现 IProfileService 接口,编写业务代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class CustomerProfileService : IProfileService { protected readonly TestUserStore Users; /// <summary> /// 案例中用户使用的还是 Quickstart.UI 模板提供的用户,所以这里通过DI 容器取到用户资源 /// </summary> /// <param name="users"></param> public CustomerProfileService(TestUserStore users) { Users = users; } public virtual Task GetProfileDataAsync(ProfileDataRequestContext context) { // 通过 用户id 找到用户 var user = Users.FindBySubjectId(context.Subject.GetSubjectId()); if (user != null ) { context.IssuedClaims.AddRange(user.Claims); } // 模拟一个用户属性 context.IssuedClaims.Add( new System.Security.Claims.Claim( "blogs" , "https://limitcode.com/" )); return Task.CompletedTask; } public async Task IsActiveAsync(IsActiveContext context) { context.IsActive = true ; } } |
注入 CustomerProfileService
PostMan 测试