IdentityServer 4 自定义身份校验/通过 token获取用户信息

Demo https://github.com/MartinAaron/data_collection

在这里插入图片描述

1、自定义身份校验

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
            	//grant_type basic
                new Client
                {
                    ClientId = "xczx",
                    AccessTokenLifetime = 36000,
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("xczx".Sha256()),
                    },
                    AllowedScopes = {"api"}
                },
                // grant_type password
                new Client()
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    ClientSecrets =
                    {
                        new Secret("_123456".Sha256())
                    },
                    AllowedScopes =
                    {
                        "api", IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile
                    }
                }
            };
        }
        // ...
        //StartUp.cs
        	services.AddScoped<IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
            services.AddScoped<IProfileService, ProfileServices>();
            var builder = services.AddIdentityServer()
                .AddInMemoryClients(Conf.GetClients())
                .AddInMemoryIdentityResources(Conf.GetIdentityResourceResources())
                .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
                .AddInMemoryApiResources(Conf.GetApiResources())
                .AddInMemoryApiScopes(Conf.ApiScopes)
                .AddProfileService<ProfileServices>();

使用 ResourceOwnerPassword 类型 需要实现 IResourceOwnerPasswordValidator与IProfileService接口,进行业务密码验证与身份获取。

//ResourceOwnerPasswordValidator

 public ResourceOwnerPasswordValidator(UserRepository userRepository)
 {
    _userRepository = userRepository;
 }

 private readonly UserRepository _userRepository;

 public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
 {
     var user = await _userRepository.GetListByField("account", context.UserName);
     if (user.Count == 0)
     {
         context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant,
             "账号输入错误");
     }
     else if (user.First().Password != context.Password.ToMD5String())
     {
         context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant,
                 "密码错误")
             ;
     } 
     else
     {
         context.Result = new GrantValidationResult(
             subject: context.UserName,
             authenticationMethod: OidcConstants.AuthenticationMethods.Password);
     } 
 }

//ProfileServices
public ProfileServices(UserRepository userRepository)
{
    _userRepository = userRepository;
}

private readonly UserRepository _userRepository;

public async Task<List<Claim>> GetClaimsFromUserAsync(User user)
{
    var claims = new List<Claim>
    {
        new Claim(JwtClaimTypes.Id, user.Id.ToString()),
        new Claim(JwtClaimTypes.NickName, user.RealName),
        new Claim(type: JwtClaimTypes.Role, user.RoleId ?? ""),
        new Claim(type: JwtClaimTypes.Profile, user.DepartmentId ?? "")
    };
    await Task.CompletedTask;
    return claims;
}

/// <summary>
/// http://localhost:5002/connect/userinfo
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var userAccount = context.Subject.Claims.FirstOrDefault(c => c.Type == "sub").Value;
    var user = await _userRepository.GetListByField("account", userAccount);
    context.IssuedClaims = await GetClaimsFromUserAsync(user.First());
}

public async Task IsActiveAsync(IsActiveContext context)
{
    var userAccount = context.Subject.Claims.FirstOrDefault(c => c.Type == "sub").Value;
    var user = await _userRepository.GetListByField("account", userAccount);
    context.IsActive = user.Any();
}

别忘记注入两个实现类

获取Token http://localhost:5002/connect/token

在这里插入图片描述

通过 access_token 获取用户信息
这里 token 不加 Bearer和空格
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值