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?
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.
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.
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.
AntiForgeryToken()Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With