Web API 和 ValidateAntiForgeryToken [英] Web API and ValidateAntiForgeryToken

查看:27
本文介绍了Web API 和 ValidateAntiForgeryToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些现有的 MVC Web 服务,它们从网页中称为 AJAX 样式.这些服务利用 ValidateAntiForgeryToken 属性来帮助防止请求伪造.

We have some existing MVC web services that are called AJAX style from web pages. These services make use of the ValidateAntiForgeryToken attribute to help prevent request forgeries.

我们希望将这些服务迁移到 Web API,但似乎没有等效的防伪功能.

We are looking to migrate these services to Web API, but there appears to be no equivalent anti-forgery functionality.

我错过了什么吗?是否有不同的方法来解决使用 Web API 的请求伪造?

Am I missing something? Is there a different approach to addressing request forgeries with Web API?

推荐答案

你可以实现这样的授权属性:

You could implement such authorization attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        try
        {
            AntiForgery.Validate();
        }
        catch
        {
            actionContext.Response = new HttpResponseMessage 
            { 
                StatusCode = HttpStatusCode.Forbidden, 
                RequestMessage = actionContext.ControllerContext.Request 
            };
            return FromResult(actionContext.Response);
        }
        return continuation();
    }

    private Task<HttpResponseMessage> FromResult(HttpResponseMessage result)
    {
        var source = new TaskCompletionSource<HttpResponseMessage>();
        source.SetResult(result);
        return source.Task;
    }
}

然后用它装饰你的 API 操作:

and then decorate your API actions with it:

[ValidateAntiForgeryToken]
public HttpResponseMessage Post()
{
    // some work
    return Request.CreateResponse(HttpStatusCode.Accepted);
}

这篇关于Web API 和 ValidateAntiForgeryToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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