Handle Anti forgery errors during logging in while

2019-04-22 02:44发布

When a user is Logged in, and goes to Login Page while so. If he tries to login again you get Anti forgery Error.

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.

Another type of error I get is:

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

How to handle this Anti forgery Errors?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-22 03:36

Create action filter inhering HandleErrorAttribute as following example. Then you can check the request and handle the error.

public class AntiForgeryHandleErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is HttpAntiForgeryException)
            {
                var url = string.Empty;
                if (!context.HttpContext.User.Identity.IsAuthenticated)
                {
                    var requestContext = new RequestContext(context.HttpContext, context.RouteData);
                    url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new {Controller = "User", action = "Login"})).VirtualPath;
                }
                else
                {
                    context.HttpContext.Response.StatusCode = 200;
                    context.ExceptionHandled = true;
                    url = GetRedirectUrl(context);
                }
                context.HttpContext.Response.Redirect(url, true);
            }
            else
            {
                base.OnException(context);
            }
        }

        private string GetRedirectUrl(ExceptionContext context)
        {
            try
            {
                var requestContext = new RequestContext(context.HttpContext, context.RouteData);
                var url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new { Controller = "User", action = "AlreadySignIn" })).VirtualPath;

                return url;
            }
            catch (Exception)
            {
                throw new NullReferenceException();
            }
        }
    }

This is my example, remember you have to handle your redirect sections depends on your request and requirements.

Then the login

[HttpPost]
        [AllowAnonymous]
        [AntiForgeryHandleError]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(UserLoginViewModel model, string returnUrl)
        {
            //Your code...
        }

Edited for comment

Use another controller / action as AlreadySignIn()

Controller code

public ActionResult AlreadySignIn()
        {
            return View();
        }

Razor View

@using Microsoft.AspNet.Identity
@{
    ViewBag.Title = "Switch Accounts";
    Layout = "~/Views/Shared/_LayoutLoginRegister.cshtml";
}
<div class="col-md-12">
    <div class="block-flat text-center" style="padding: 20px; margin-bottom: 0; padding-bottom: 0;">

        <i class="glyphicon glyphicon-user"></i>
        <br />
        <label style="padding-bottom: 10px; padding-top: 10px">You're already signed in as <strong>@User.Identity.Name</strong></label>
        <label style="padding-bottom: 5px; padding-top: 5px">@Html.ActionLink("Remain signed in with this account.", "Login", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label>
        <label style="padding-bottom: 5px; padding-top: 2px">@Html.ActionLink("Click here to sign out and sign with a different account", "LogOff", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label>

    </div>
</div>

Hope this helps.

查看更多
登录 后发表回答