Rod*_*tes 10 c# antiforgerytoken asp.net-core identityserver4
我在ASP.NET Core 2.2中使用IdentityServer4。在Post Login方法上,我应用了ValidateAntiForgeryToken。通常,在坐在登录页面上20分钟到2个小时之后,尝试登录时会生成空白页面。
如果您查看Postman Console,则会收到400 Bad Request消息。然后,我将AntiForgery选项上的Cookie有效期设置为90天。我能够让该页面坐满6个小时,并且仍然可以登录。但是,大约8个小时(过夜)后,尝试登录后我又收到了空白页。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login
Run Code Online (Sandbox Code Playgroud)
services.AddAntiforgery(options =>
{
options.Cookie.Expiration = TimeSpan.FromDays(90);
});
Run Code Online (Sandbox Code Playgroud)
我希望能够在登录页面上停留90天,这是cookie的持续时间,但这是行不通的。如何获得AntiforgeryToken的Cookie可以持续整整90天或我设置的任何时间,而不是超时或过期?有没有一种方法可以捕获此错误并将用户重定向回登录方法?
还有另一种使用默认方法的实现,包括所有预检查,日志记录等。它仍然是AuthorizationFilter,因此可以防止进一步执行操作。唯一的区别是,它触发HttpGet的是相同的url,而不是默认的400响应(一种Post / Redirect / Get模式实现)。
public class AnotherAntiForgeryTokenAttribute : TypeFilterAttribute
{
public AnotherAntiForgeryTokenAttribute() : base(typeof(AnotherAntiforgeryFilter))
{
}
}
public class AnotherAntiforgeryFilter:ValidateAntiforgeryTokenAuthorizationFilter,
IAsyncAuthorizationFilter
{
public AnotherAntiforgeryFilter(IAntiforgery a, ILoggerFactory l) : base(a, l)
{
}
async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(
AuthorizationFilterContext ctx)
{
await base.OnAuthorizationAsync(ctx);
if (ctx.Result is IAntiforgeryValidationFailedResult)
{
// the next four rows are optional, just illustrating a way
// to save some sensitive data such as initial query
// the form has to support that
var request = ctx.HttpContext.Request;
var url = request.Path.ToUriComponent();
if (request.Form?["ReturnUrl"].Count > 0)
url = $"{url}?ReturnUrl={Uri.EscapeDataString(request.Form?["ReturnUrl"])}";
// and the following is the only real customization
ctx.Result = new LocalRedirectResult(url);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
274 次 |
| 最近记录: |