登录页面上的防伪标记

问题描述 投票:19回答:4

我在登录页面上实现了防伪令牌。

现在我有一个用户按下键盘上的后退键,当他们在填写凭据后再次点击登录按钮时,他们会收到错误页面。

有没有更好的方法来处理这种情况,如将它们重定向到新的登录页面?

登录页面是:/ account / logon

如果登录详细信息已成功,则用户将被重定向到:主页/索引页面,用户在该页面上按下按钮。

c# asp.net-mvc-3 antiforgerytoken
4个回答
20
投票

不要在登录页面上实现ASP.NET AntiForgeryToken。令牌基于其他条件中的用户名,登录页面假定攻击者已拥有系统凭据,以便能够利用该页面上的csrf。

但是,您应该在登录页面上使用某种形式的CSRF保护 - 请参阅https://security.stackexchange.com/a/2126/51772


7
投票

我在这里写了一个完整的解决方案:https://richardcooke.info/en/2014/keep-users-signed-in-after-asp-net-deploy/

这是从您的控制器调用GET方法所需的代码:

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));
}

和代码放在你的视图中代替Html.AntiForgeryToken():

@if (ViewBag.FormToken != null)
{
    <text><input name="__RequestVerificationToken" type="hidden" value="@ViewBag.FormToken" /></text>
}
else
{
    <text>@Html.AntiForgeryToken()</text>
}

5
投票

我的解决方案是:

如果再次点击登录页面,请重新加载页面。这将确保防伪标记的新装载

一切都完成了


0
投票

而不是像提到的其他帖子一样检查User.Identity.IsAuthenticated我使用自定义属性来处理异常并将用户重定向到主页,如果它是HttpAntiForgeryToken

我相信这避免了使用其他方法的任何潜在安全问题,并且应始终在POST方法上使用[ValidateAntiForgeryToken]

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;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.