【问题标题】:Use AntiForgeryToken with ASP.NET 5 and Angular将 AntiForgeryToken 与 ASP.NET 5 和 Angular 一起使用
【发布时间】:2016-08-26 06:40:40
【问题描述】:

在 ASP.NET 5 RC1 上,我有以下内容

[HttpPost]
public async Task<IActionResult> Create([FromBody]Post post) {
  // Create post
}

我有一个 Angular 使用的 CreatePost.html 模板,格式如下:

<form ng-controller="CreatePostController" ng-submit="create()">
  <label>Title</label>
  <input type="text" name="title">
  <label>Content</label>
  <input type="text" name="content">
  <button type="submit">Create</button>
</form>
  1. 在 HTML 页面中。如何呈现 ASP.NET AntiForgeryToken? 我可以在页眉上创建一个并在我的所有网站表单上使用吗?

  2. 调用API并验证时如何发送token?

【问题讨论】:

标签: asp.net angularjs asp.net-core


【解决方案1】:
  1. 使用 AngularJS 在标头中设置防伪令牌一次 $http 服务
    1. 公开一个web api方法返回防伪 令牌。

看看这篇文章:http://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

【讨论】:

  • 投了赞成票。这是我在做同样事情时添加书签的页面。 link
【解决方案2】:

在 asp.net core rc1 中有一个防伪中间件。你可以使用它。这是我写的关于如何实现这一目标的简单博客。

http://fiyazhasan.me/angularjs-anti-forgery-with-asp-net-core/

【讨论】:

  • 这应该是评论
【解决方案3】:

如果您使用的是 ui-router,您可以执行以下操作。这种方法的美妙之处在于它只发生在状态更改而不是对服务器的每个请求上。如果您正在开发 SPA,并使用任何模板,这将派上用场:

       $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (IsAuthenticated()) {
                SetAntiForgeryCookie();
            }
        });

SetAntiForgeryCookey 只是执行一个调用简单操作的 $http GET 请求:

    [HttpGet]
    public IActionResult Get()
    {
        var context = Request.HttpContext;
        var tokens = _antiForgery.GetAndStoreTokens(context);
        context.Response.Cookies
            .Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });

        return new ObjectResult(true);
    }

然后我创建一个属性以应用于我的操作:

public class ValidateApiAntiForgeryTokenAttribute : ActionFilterAttribute
{
    private readonly IAntiforgery _antiForgery;

    public ValidateApiAntiForgeryTokenAttribute(IAntiforgery antiForgery)
    {
        _antiForgery = antiForgery;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        await _antiForgery.ValidateRequestAsync(context.HttpContext);
        await base.OnActionExecutionAsync(context, next);
    }
}

我唯一不喜欢这种方法的是,为了注入属性,我必须在操作上使用 ServiceFilterAttribute:

[ServiceFilter(typeof(ValidateApiAntiForgeryTokenAttribute))]

另外不要忘记 ConfigureServices 中的中间件:

 services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2018-06-25
    • 2014-09-15
    • 2014-12-22
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多