本文介绍了OpenID Connect:如何在客户端凭据流中添加自定义声明数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我的身份服务器设置客户端凭据流,以从客户端获取访问令牌.我可以使用以下代码获取访问令牌,

I'm setting up a client credential flow with my identity server to get an access token from a client. I'm able to get the access token with the following code,

  • 身份服务器配置:

 public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var corsPolicyService = new DefaultCorsPolicyService()
        {
            AllowAll = true
        };

        var idServerServiceFactory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get())
        .UseInMemoryUsers(Users.Get());

        var options = new IdentityServerOptions
        {
            Factory = idServerServiceFactory,
            SiteName = "Demo",
            IssuerUri = IdentityConstants.IssuerUri,
            PublicOrigin = IdentityConstants.STSOrigin,
            SigningCertificate = LoadCertificate()
        };

        idsrvApp.UseIdentityServer(options);
    });
}

  • 身份服务器 - 客户端配置:

    public static class Clients
    {
        public static IEnumerable<Client> Get()
        {
        return new[]
         {
            new Client
            {
                 ClientId = "ClientSDK",
                 ClientName = "Client SDK (Client Credentials)",
                 Flow = Flows.ClientCredentials,
                 AllowAccessToAllScopes = true,
    
                ClientSecrets = new List<Secret>()
                {
                    new Secret(IdentityConstants.ClientSecret.Sha256())
                }
            }
         };
    }
    

    }

    MVC 客户端:

      var oAuth2Client = new TokenClient(
                  IdentityConstants.STSTokenEndpoint,
                  "ClientSDK",
                    IdentityConstants.ClientSecret);
    
        var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("MyScope").Result;
    
        return tokenResponse.AccessToken;
    

  • 我能够获得访问令牌(即 JWT).请告诉我如何在创建令牌时使用其声明数据创建 JWT 时,如何从我的数据库中添加一个唯一键,例如 (UserId).

    I'm able to get the access token(i.e. JWT). Can one please tell me how to add a unique key like (UserId) from my database, when the JWT is created with its claims data when the token is created.

    推荐答案

    您应该实现自定义用户存储以验证用户并从数据库添加声明.更改启动代码如下,Userrepository 类代表数据库通信以验证用户并从数据库中获取声明:

    You should implement custom user store for validating user and adding claims from database. Change startup code like below, Userrepository class represents database communication to authenticate user and get claims from database:

    var idServerServiceFactory = new IdentityServerServiceFactory()
       .UseInMemoryClients(Clients.Get())
       .UseInMemoryScopes(Scopes.Get())
       .AddCustomUserStore();
    

    添加以下类并根据您的要求进行更改:

    Add below classes and change according to your requirement:

    public static class CustomIdentityServerBuilderExtensions
    {
        public static IIdentityServerBuilder AddCustomUserStore(this IIdentityServerBuilder builder)
        {
            builder.AddProfileService<UserProfileService>();
            builder.AddResourceOwnerValidator<UserResourceOwnerPasswordValidator>();
            return builder;
        }
    }
    
    public class UserProfileService : IProfileService
    {
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
                UserRepository userRepository=new UserRepository();
                var user = userRepository.GetUserById(int.Parse(context.Subject.GetSubjectId()));
                if (user != null)
                {
                    var userTokenModel = _mapper.Map<UserTokenModel>(user);
                    var claims = new List<Claim>();
                    claims.Add(new Claim("UserId", user.UserId));
                    // Add another claims here
                    context.IssuedClaims.AddRange(claims);
        }
        public async Task IsActiveAsync(IsActiveContext context)
        {
        }
    }
    
    public class UserResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
                UserRepository userRepository=new UserRepository();
                var userLoginStatus = userRepository.GetUserById(context.UserName, context.Password);
    
                if (userLoginStatus != null)
                {
    
                        context.Result = new GrantValidationResult(userLoginStatus.UserId.ToString(),
                             OidcConstants.AuthenticationMethods.Password);
                }
                else
                {
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient,
                            "Wrong Credentials");
                }
        }
    }
    

    这篇关于OpenID Connect:如何在客户端凭据流中添加自定义声明数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-24 15:20