IdentityServer4实战:Token 中返回用户属性

前言

在前几篇的学习中,生成的 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 测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值