Asp.NET核心OpenIddict invalid_grant
第一件事第一:我知道这是一个大的帖子,但我跟踪这个问题几个星期,我收集了很多信息可能是问题的根源。Asp.NET核心OpenIddict invalid_grant
我正在使用OpenIddict身份验证的Angular2应用程序。我在客户端应用程序上获取access_token,refresh_token。我可以使用refresh_token来获取新的access_token,一切正常。几乎。
在某些时候,我从服务器获取错误响应:
POST https://mydomain:2000/api/authorization/token 400(错误请求)
和响应:
error:"invalid_grant"
error_description:"Invalid ticket"
我三重检查一切和refresh_token我发送的是正确的。
关于设计:
在向服务器发出请求之前,我检查access_token是否过期。如果过期,我发送请求以获取带有refresh_token的新access_token。
它适用于随机时间,但在一些随机时间(重复)refresh_token变得无效。
我虽然它与AddEphemeralSigningKey
有关,我把它改为AddSigningCertificate
。 (详细信息请参见this线程。)
我认为,IIS在经过一段时间的活动后会杀死Kestrel。我的应用程序池的配置是:
StartMode: OnDemand
Idle Time-out (minutes): 20
Idle Time-out (action): Terminate
我怀疑新的请求之后,OpenIddict错误地去地下室refresh_token,因为红隼重新启动?或者我错了?
我也检查OpenIddict表和OpenIddictApplications,OpenIddictAuthorizations和OpenIddictScopes都是空的。只有OpenIddictTokens包含一些数据(以及所有的类型都是refresh_token):
我会想到,这是refresh_tokens地方保存。 哪里?也许这是源代码问题,为什么我的refresh_tokens在一些随机时间后失效(也许当Kestrel重新启动时)。
IIS日志:
Hosting environment: Production
Content root path: D:\Podatki\OpPISWeb\WWWProduction
Now listening on: http://localhost:1408
Application started. Press Ctrl+C to shut down.
fail: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
The token request was rejected because the authorization code or the refresh token was invalid.
fail: AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware[0]
The token request was rejected because the authorization code or the refresh token was invalid.
这里是我的启动。CS:
public void ConfigureServices(IServiceCollection services)
{
try
{
services.Configure<IISOptions>(options =>
{
});
services.AddMvc();
services.AddMvcCore().AddDataAnnotations();
services.AddEntityFrameworkSqlServer();
services.AddScoped<UserStore<AppUser, AppRole, AppDbContext, int, AppUserClaim, AppUserRole, AppUserLogin, AppUserToken, AppRoleClaim>, AppUserStore>();
services.AddScoped<UserManager<AppUser>, AppUserManager>();
services.AddScoped<RoleManager<AppRole>, AppRoleManager>();
services.AddScoped<SignInManager<AppUser>, AppSignInManager>();
services.AddScoped<RoleStore<AppRole, AppDbContext, int, AppUserRole, AppRoleClaim>, AppRoleStore>();
var connection = Configuration["ConnectionStrings:Web"];
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(connection);
options.UseOpenIddict<int>();
if (this.env.IsDevelopment())
options.EnableSensitiveDataLogging();
});
services
.AddIdentity<AppUser, AppRole>()
.AddUserStore<AppUserStore>()
.AddUserManager<AppUserManager>()
.AddRoleStore<AppRoleStore>()
.AddRoleManager<AppRoleManager>()
.AddSignInManager<AppSignInManager>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});
services.AddOpenIddict<int>(options =>
{
options.AddEntityFrameworkCoreStores<AppDbContext>();
options.AddMvcBinders();
options.EnableTokenEndpoint("/API/authorization/token");
options.AllowPasswordFlow();
options.AllowRefreshTokenFlow();
options.AllowCustomFlow("urn:ietf:params:oauth:grant-type:google_identity_token");
options.AllowCustomFlow("urn:ietf:params:oauth:grant-type:logedin");
options.UseJsonWebTokens();
if (this.env.IsDevelopment())
options.AddEphemeralSigningKey();
else
options.AddSigningCertificate(new FileStream(
Directory.GetCurrentDirectory() + "/Resources/cert.pfx", FileMode.Open), "password");
options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30));
options.SetRefreshTokenLifetime(TimeSpan.FromDays(14));
if (this.env.IsDevelopment())
options.DisableHttpsRequirement();
});
services.AddSingleton<DbSeeder>();
services.AddSingleton<IConfiguration>(c => { return Configuration; });
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
{
loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(this.Configuration["Directories:Upload"]),
RequestPath = new PathString("/Files")
});
app.UseOpenIddict();
var JwtOptions = new JwtBearerOptions()
{
Authority = this.Configuration["Authentication:OpenIddict:Authority"],
Audience = "OpPISWeb",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false
};
JwtOptions.RequireHttpsMetadata = !env.IsDevelopment();
app.UseJwtBearerAuthentication(JwtOptions);
app.UseMvc();
using (var context = new AppDbContext(this.Configuration))
{
context.Database.Migrate();
}
try
{
dbSeeder.SeedAsync();
}
catch (AggregateException e)
{
throw new Exception(e.ToString());
}
}
更新:
最终我不得不这样做是:
services.AddDataProtection()
.SetApplicationName(this.Configuration["Authentication:ApplicationId"])
.PersistKeysToFileSystem(new DirectoryInfo(this.Configuration["Directories:Keys"]));
不要忘记添加权限到IIS的目录:密钥文件夹。
我认为,refresh_tokens保存在某个地方。哪里?
不通。由OpenIddict发布的授权码,刷新令牌和访问令牌(使用默认格式时)为自包含,并且从未出于安全原因(仅与主题相关的元数据或与令牌关联的授权标识符一起)存储。
您看到的问题很可能是由于您尚未配置环境以正确保留由OpenIddict依赖的ASP.NET Core Data堆栈使用的加密密钥来加密其令牌所导致的问题。你可以阅读OpenIddict: 401 errors when two or more service instance count了解更多关于如何解决这个问题的信息。
@Pinpint:我认为这是事实。当另一个用户登录时会出现问题。有没有推荐的方法来执行此操作。我检查你的例子,阅读相关主题。也许几行代码我该怎么做。 谢谢。 – Makla