Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API and 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.

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

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

like image 334
ScottS Avatar asked Jul 13 '12 19:07

ScottS


People also ask

Does web API need AntiForgeryToken?

There is no additional work required to validate an anti-forgery token in an API request, because the [ValidateAntiForgeryToken] attribute in ASP.NET Core will look for tokens in a posted form input, or in an HTTP header. But, there is some additional work required to give the client a token.

What is ValidateAntiForgeryToken?

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks. A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user.

What is ValidateAntiForgeryToken ASP NET core?

HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests. ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.

What is the use of HTML AntiForgeryToken () in MVC?

AntiForgeryToken()Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.


1 Answers

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

and then decorate your API actions with it:

[ValidateAntiForgeryToken] public HttpResponseMessage Post() {     // some work     return Request.CreateResponse(HttpStatusCode.Accepted); } 
like image 93
Darin Dimitrov Avatar answered Sep 21 '22 12:09

Darin Dimitrov