IdentityServer4 Identity Resource中的user Claim

 

Identity Resource

身份资源,里面的UserClaims是用户的一些属性,默认情况下,即使写再多的属性,token中也只会返回sub一个,我们需要在代码中加入

 var builder = services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.Apis)
                .AddInMemoryClients(Config.Clients)
             .AddTestUsers(TestUsers.Users)
            .AddProfileService<ProfileService>();
            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();

然后去实现IProfileService

 public class ProfileService : IProfileService
    {
        protected readonly TestUserStore Users;
        public ProfileService(TestUserStore users)
        {
            Users = users;
        }
   
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于 IdentityServer4 从数据库获取 User 进行授权验证,可以通过实现接口 `IProfileService` 来实现。 具体步骤如下: 1. 实现 `IProfileService` 接口。 ```csharp public class ProfileService : IProfileService { private readonly IUserRepository _userRepository; public ProfileService(IUserRepository userRepository) { _userRepository = userRepository; } public async Task GetProfileDataAsync(ProfileDataRequestContext context) { var subject = context.Subject; var user = await _userRepository.GetUserByIdAsync(subject.GetSubjectId()); if (user != null) { var claims = new List<Claim> { new Claim("user_id", user.Id), new Claim("username", user.Username), new Claim("email", user.Email) }; context.IssuedClaims = claims.Where(x => context.RequestedClaimTypes.Contains(x.Type)).ToList(); } } public async Task IsActiveAsync(IsActiveContext context) { var subject = context.Subject; var user = await _userRepository.GetUserByIdAsync(subject.GetSubjectId()); context.IsActive = user != null; } } ``` 2. 注册 `IProfileService` 接口。 ```csharp services.AddTransient<IProfileService, ProfileService>(); ``` 3. 在 `Startup` 类的 `ConfigureServices` 方法,注入 `IUserRepository` 接口。 ```csharp services.AddScoped<IUserRepository, UserRepository>(); ``` 4. 在 `IdentityServer` 的配置,将 `IProfileService` 接口实现注入。 ```csharp services.AddIdentityServer() .AddProfileService<ProfileService>() // ... ``` 需要注意的是,`IUserRepository` 接口可以根据实际情况进行实现。在 `ProfileService` 实现,我们根据 `context.Subject` 获取了当前用户的信息,并将需要的信息添加到了 `context.IssuedClaims` 。如果用户不存在,则 `IsActiveAsync` 方法返回 `false`。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值