IdentityServer4
IdentityServer4:2.3.2版本基于数据库的请求token失效
- 这个问题出现在2.3.2版本内,我去看了下源码,原因如下:
////// Adds the validators. /// /// The builder. ///public static IIdentityServerBuilder AddValidators(this IIdentityServerBuilder builder) { // core builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); // optional builder.Services.TryAddTransient (); builder.Services.TryAddTransient (); return builder; }
重点在这里:
builder.Services.TryAddTransient<IResourceOwnerPasswordValidator, NotSupportedResourceOwnerPasswordValidator>();
- NotSupportedResourceOwnerPasswordValidator.cs
public class NotSupportedResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator { private readonly ILogger _logger; ////// Initializes a new instance of the /// The logger. public NotSupportedResourceOwnerPasswordValidator(ILoggerclass. /// logger) { _logger = logger; } /// /// Validates the resource owner password credential /// /// The context. ///public Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { context.Result = new GrantValidationResult(TokenRequestErrors.UnsupportedGrantType); _logger.LogInformation("Resource owner password credential type not supported. Configure an IResourceOwnerPasswordValidator."); return Task.CompletedTask; } }
- 可以看到ValidateAsync这里直接返回了UnsupportedGrantType,所以说我们要把这个给下。方法如下:
-
修改我们的IdentityServer服务器的StartUp.cs:
services.AddIdentityServer() .AddDeveloperSigningCredential() // this adds the config data from DB (clients, resources) .AddConfigurationStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); }) // this adds the operational data from DB (codes, tokens, consents) .AddOperationalStore(options => { options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); // this enables automatic token cleanup. this is optional. options.EnableTokenCleanup = true; options.TokenCleanupInterval = 30; }).Services.Replace(ServiceDescriptor.Transient());
- 这里我是把IResourceOwnerPasswordValidator的注入服务给替换了一下,用自己的验证逻辑来做。这个验证逻辑参考