Skip to content

Instantly share code, notes, and snippets.

@feanz
Created January 31, 2014 09:40
Show Gist options
  • Save feanz/86fa21a0cea1310315e8 to your computer and use it in GitHub Desktop.
Save feanz/86fa21a0cea1310315e8 to your computer and use it in GitHub Desktop.
Validate AntiForgery Token Attribute that could be used for web api
[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
{
//could add optional ajax header check here
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment