【问题标题】:How to add Html.AntiForgeryToken to ActionLink and RedirectToAction?如何将 Html.AntiForgeryToken 添加到 ActionLink 和 RedirectToAction?
【发布时间】:2013-09-12 14:32:48
【问题描述】:

我在添加 AntiForgeryToken 时遇到问题。这是我的代码:

<%:Html.ActionLink("Text", "Action", new { ID = "Hello")})%>

 RedirectToAction("Action", "Controller", new { ID = "HelloFromMe"});

控制器:

[ValidateAntiForgeryToken]
public ActionResult Action(String ID){
return View();
}

有人知道怎么做吗?

【问题讨论】:

  • 为什么要在 GET 方法中使用 AntiForgeryToken?
  • 因为我传递的 ID 对应于 TempData 中的键。我希望请求包含验证令牌(甚至是获取请求)。

标签: c# html asp.net asp.net-mvc


【解决方案1】:

不可能在 GET 方法中使用 AntiForgeryToken。

GET 方法只能用于服务器上的只读操作。如果你想做一些只读操作以外的事情,那么你应该使用 POST 方法。

这里是这个令牌有用的原因,如何以及何时使用它。 http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx

【讨论】:

  • 好的。谢谢您的回复:)
  • 我添加了一个解释see-surf攻击(CSRF)的链接
  • 所以我们应该切换到丑陋的表单帖子,而不是像“删除”或“隐藏”这样漂亮的链接按钮?使用链接是完全可以的,至少可以避免来回时出现“再次发布表单”的问题。本机 ValidateAntiForgeryToken 不适用于链接,但自定义链接可以正常工作。
  • @ADOConnection 你不知道javascript吗?
【解决方案2】:

防伪令牌的思想是防止攻击者代表用户生成 POST / GET 请求。这就是为什么我们为每个 POST / GET 请求添加一些特殊的东西,攻击者不知道。

自定义防伪的最简单实现如下所示。 而且它和 ValidateAntiForgeryToken 一样安全。

public class ProfileController : AuthorizedAccessController
{
    // GET
    public ActionResult Details(int userId)
    {
        User user = this.Entities.User.First(u => u.Id == userId);

        this.Session["ProfilePageAntiforgery"] = Guid.NewGuid(); // use RandomNumberGenerator to generate strong token 
        this.ViewBag.ProfilePageAntiforgery = this.Session["ProfilePageAntiforgery"];

        return View(user);
    }

    public ActionResult DeleteMyProfile(int userId, string profilePageAntiforgery)
    {
        if ((string)this.Session["ProfilePageAntiforgery"] != profilePageAntiforgery)
        {
            return this.RedirectToAction("Details", new { userId });
        }

        User user = this.Entities.User.First(u => u.Id == userId);
        this.Entities.User.Remove(user);

        this.Entities.SaveChanges();

        return this.RedirectToAction("ProfileDeleted");
    }
}

查看:

<div>
     @Html.ActionLink("Delete my profile", "DeleteMyProfile", new {userId = this.Model.Id, profilePageAntiforgery = this.ViewBag.ProfilePageAntiforgery })
</div>

从中制作自定义属性是一个技术问题。 假设一个属性将令牌存储在 session 和 viewbag 中,另一个用于验证。

如果使用 Session 不合适(网络农场等),您可以简单地用 DB 或其他存储替换它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多