与 asp.net-core 中的 AntiForgery.Validate() 等效的命令 [英] Command equivalent to AntiForgery.Validate() in asp.net-core

查看:30
本文介绍了与 asp.net-core 中的 AntiForgery.Validate() 等效的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 asp.net-core 中存在一个类似于 AntiForgery.Validate(); 的命令来验证动作主体中的防伪令牌?

Exists, in asp.net-core, a command similar to AntiForgery.Validate(); to validate antiforgery token in the action body?

dotnet 4.5.1 中的代码示例:

Code example in dotnet 4.5.1:

public ActionResult Index()
{
    if (!User.Identity.IsAuthenticated)
    {
        System.Web.Helpers.AntiForgery.Validate();
    }

    // rest of action
}

推荐答案

可以使用控制器中的过滤器属性自动完成防伪令牌验证.

Antiforgery token validation can be done automatically using filter attributes in your controllers.

  • 使用 [AutoValidateAntiforgeryToken] 在所有不安全"方法上验证令牌.(GET、HEAD、TRACE、OPTIONS 以外的方法).
  • 使用 [ValidateAntiforgeryToken] 始终验证令牌
  • 使用 [IgnoreAntiforgeryToken] 忽略令牌验证
  • Use [AutoValidateAntiforgeryToken] to validate the token on all "unsafe" methods. (Methods other than GET, HEAD, TRACE, OPTIONS).
  • Use [ValidateAntiforgeryToken] to always validate the token
  • Use [IgnoreAntiforgeryToken] to ignore token validation

您可以组合这些属性来实现您需要的粒度.例如:

You can combine these attributes to achieve the granularity you need. For example:

//Validate all 'unsafe' actions except the ones with the ignore attribute
[AutoValidateAntiforgeryToken]
public class MyApi: Controller
{
    [HttpPost]
    public IActionResult DoSomething(){ }
    [HttpPut]
    public IActionResult DoSomethingElse(){ }

    [IgnoreAntiforgeryToken]   
    public IActionResult DoSomethingSafe(){ }
}

//Validate only explicit actions
public class ArticlesController: Controller
{
    public IActionResult Index(){ }

    [ValidateAntiforgeryToken]
    [HttpPost]   
    public IActionResult Create(){ }
}

我注意到 docs 站点,但您可以在 github 问题.

I have noticed the documentation isnt fully ready in the docs site, but you can see a draft of it in the github issue.

这篇关于与 asp.net-core 中的 AntiForgery.Validate() 等效的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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