“返回"按钮和防伪令牌 [英] The "Back" button and the anti-forgery token

查看:93
本文介绍了“返回"按钮和防伪令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到与防伪属性相关的Runtime error.

I'm getting a Runtime error related the the anti-forgery attribute.

执行以下步骤:

  1. 创建MVC Web应用程序并启动
  2. 注册 joe@acme.org
  3. 退出
  4. 注册 jane@acme.org
  5. 退出
  6. joe@acme.org
  7. 登录
  8. 点击后退按钮
  9. jane@acme.org
  10. 登录
  1. Create an MVC web application and start
  2. Register joe@acme.org
  3. Sign out
  4. Register jane@acme.org
  5. Sign out
  6. Login as joe@acme.org
  7. Hit the back button
  8. Login as jane@acme.org

错误: The provided anti-forgery token was meant for a different claims-based user than the current user.

可以采取什么措施来防止发生此错误?

What can be done to prevent this error from occurring?

推荐答案

这是一种忽略错误并使用户返回登录屏幕的方式.这只是一个例子.

This is one way of ignoring the error and returning the user to the login screen. It's just an example.

创建一个名为HandleAntiforgeryTokenErrorAttribute的新类,该类继承自HandleErrorAttribute.覆盖OnException方法.

Create a new class called HandleAntiforgeryTokenErrorAttribute that inherits from HandleErrorAttribute. Override the OnException method.

public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(new { action = "Login", controller = "Account" }));
    }
}

转到您的FilterConfig类并将该属性注册为全局过滤器.

Go to your FilterConfig class and register the attribute as a global filter.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new HandleAntiforgeryTokenErrorAttribute()
            { ExceptionType = typeof(HttpAntiForgeryException) }
        );
    }
}

这篇关于“返回"按钮和防伪令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆