我有一个基本的IdentityServer4令牌服务器、一个Api和一个基于client_credentials文档教程的使用client_credentials的测试客户端应用程序设置。
我们有一个预先构建好的客户端应用程序,用户可以用他们现有的凭据登录到这个应用程序中,这并不绑定到IdentityServer4中。客户端应用程序将使用client_credentials工作流调用Api,因为我不希望为可能需要访问Api的每个客户端应用程序创建多个用户。
使用上面使用IdentityServer4的设置,我可以正确地处理client_Credentials工作流。我面临的问题是,虽然我不需要单个用户进行身份验证,但我仍然希望通过user_id知道他们是谁。我可以简单地将&user_id=9999添加到令牌请求中,但是在发出请求时,我找不到从令牌服务器检索此信息的方法。经过一些研究,我发现了IExtensionGrantValidator,它允许我添加自定义授予类型并拦截请求并进行一些自定义处理。问题是,即使看起来我正确地设置了它,我仍然得到了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>();我是IdentityServer4和.net核心的新手,所以我肯定我做错了什么,或者不理解这里的基本机制。
发布于 2020-03-19 14:24:11
为了获得一个具有成功答案的IExtensionGrantValidator,您必须实现接口IProfileService。这个接口有一个名为IsActiveAsync的方法。如果不实现此方法,ValidateAsync的回答将始终是假的。这里我将向您展示一个实现示例:
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
}您的实现可以(我认为这将是)更复杂,但我希望这给您和良好的起点。
发布于 2018-01-16 01:11:49
我发现这是因为我有同样的错误问题,但我确信您的验证程序是无用的,因为它什么也不做。您需要在上下文中设置如下结果:
var claims = new List<Claim>();
claims.Add(new Claim("sub", userToken));
claims.Add(new Claim("role", "admin"));
context.Result = new GrantValidationResult(userToken, "delegation", claims: claims);我看到的每个示例都通过添加这个值来设置结果。
https://stackoverflow.com/questions/46709364
复制相似问题