网页API和ValidateAntiForgeryToken [英] Web API and ValidateAntiForgeryToken

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

问题描述

我们有一个被称为从网页AJAX风格的一些现有的MVC的Web服务。这些服务利用ValidateAntiForgeryToken的属性,以帮助prevent请求伪造。

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

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

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