I have implemented antiforgery token on my login page.
Now I had one user pressing back key on the keyboard, and when they click on login button again after filling
Don't implement the ASP.NET AntiForgeryToken on your login page. The token is based on a username among other criteria and a login page assume the attacker already has credentials to a system in order to be able to exploit csrf on that page.
However, you should use some form of CSRF protection on your login page - see https://security.stackexchange.com/a/2126/51772
My solution to this was:
Reload a page if it hits login page again. this will ensure fresh loading of antiforgery token
and all is done
I've written up a full solution here: https://richardcooke.info/en/2014/keep-users-signed-in-after-asp-net-deploy/
Here's the necessary code to call in your controller form your GET method:
private void SetANewRequestVerificationTokenManuallyInCookieAndOnTheForm()
{
if (Response == null)
return;
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
SetCookie("__RequestVerificationToken", cookieToken);
ViewBag.FormToken = formToken;
}
private void SetCookie(string name, string value)
{
if (Response.Cookies.AllKeys.Contains(name))
Response.Cookies[name].Value = value;
else
Response.Cookies.Add(new HttpCookie(name, value));
}
and code to put in your view in place of Html.AntiForgeryToken():
@if (ViewBag.FormToken != null)
{
<text><input name="__RequestVerificationToken" type="hidden" value="@ViewBag.FormToken" /></text>
}
else
{
<text>@Html.AntiForgeryToken()</text>
}
Instead of checking User.Identity.IsAuthenticated like some other posts mentioned I used a custom attribute to handle the exceptions and redirect the user to the home page if it is a HttpAntiForgeryToken
I believe this avoids any potential security concerns of using the other methods, and that [ValidateAntiForgeryToken] should always be used on POST methods
public override void OnException(ExceptionContext filterContext)
{
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
if (filterContext.Exception is HttpAntiForgeryException)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Index" },
{ "controller", "Home" }
});
filterContext.ExceptionHandled = true;
}
}