新文章 网摘 文章 随笔 日记

IdentityServer4 IExtensionGrantValidator

我有一个基本的 IdentityServer4 令牌服务器、一个 Api 和一个使用基于 identityserver4 文档教程的 client_credentials 的测试客户端应用程序设置。

我们有一个预先构建的客户端应用程序,用户可以使用与 IdentityServer4 无关的现有凭据登录该应用程序。客户端应用程序将使用 client_credentials 工作流调用 Api,因为我不想为每个可能需要访问 Api 的客户端应用程序创建多个用户。

将上述设置与 IdentityServer4 一起使用,我可以在 client_Credentials 工作流中正常工作。我面临的问题是,虽然我不需要个人用户对自己进行身份验证,但我仍然想通过 user_id 了解他们是谁。我可以简单地将 &user_id=9999 添加到令牌请求中,但是我找不到在发出请求时从令牌服务器检索此信息的方法。经过一些研究,我遇到了 IExtensionGrantValidator,它允许我添加一个 cstom 授权类型并拦截请求并进行一些自定义处理。问题是即使看起来我设置正确,我仍然收到 invalid_grant 错误。

这是代码:

public class CustomGrantValidator : IExtensionGrantValidator
{
    public string GrantType => "custom_credentials";

    public Task ValidateAsync(ExtensionGrantValidationContext context)
    {
        return Task.FromResult(context.Result);
    }
}

在新的客户端块中:

 AllowedGrantTypes =
 {
     GrantType.ClientCredentials,
     "custom_credentials"
 },

启动中

.AddExtensionGrantValidator<CustomGrantValidator>();.

为了获得 IExtensionGrantValidator 的成功答案,您必须实现接口 IProfileService。这个接口有一个叫做 IsActiveAsync 的方法。如果不实现该方法,ValidateAsync 的答案将始终为 false。在这里,我将向您展示一个实现示例:

public class IdentityProfileService : IProfileService
    {

        //This method comes second
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            //IsActiveAsync turns out to be true 
            //Here you add the claims that you want in the access token
            var claims = new List<Claim>();

            claims.Add(new Claim("ThisIsNotAGoodClaim", "MyCrapClaim"));

            context.IssuedClaims = claims;
        }

        //This method comes first
        public async Task IsActiveAsync(IsActiveContext context)
        {           
            bool isActive = false;
            /*
                Implement some code to determine that the user is actually active 
                and set isActive to true
            */
            context.IsActive = isActive;
        }
    }

然后,您必须在启动页面中添加此实现。

public void ConfigureServices(IServiceCollection services)
{

    // Some other code
services.AddIdentityServer()
                    .AddDeveloperSigningCredential()
                    .AddAspNetIdentity<Users>()
                    .AddInMemoryApiResources(config.GetApiResources())
                    .AddExtensionGrantValidator<CustomGrantValidator>()
                    .AddProfileService<IdentityProfileService>();
    // More code
}

您的实现可以(而且我认为会)更复杂,但我希望这可以为您提供良好的起点。

 

https://stackoverflow.com/questions/46709364/identityserver4-iextensiongrantvalidator

 
posted @ 2021-12-01 10:54  岭南春  阅读(597)  评论(0)    收藏  举报