Skip to content

Instantly share code, notes, and snippets.

@brainded
Created June 20, 2014 23:53
Show Gist options
  • Save brainded/fc1e1c643527c9888e2f to your computer and use it in GitHub Desktop.
Save brainded/fc1e1c643527c9888e2f to your computer and use it in GitHub Desktop.
ValidateAntiForgeryTokenAttribute for WebApi and how to use it.
var authorizationToken = $("#antiforgerytoken").val();
$.ajax({
type:"POST",
beforeSend: function (request) {
request.setRequestHeader("RequestVerificationToken", authorizationToken);
},
url: "entities",
data: {
Something: "something"
},
processData: false,
success: function(msg) {
alert("Success!");
}
});
<h2>Some View</h2>
@functions
{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
<input id="antiforgerytoken" type="hidden" value="@TokenHeaderValue()" />
/// <summary>
/// Validate AntiForgery Token Attribute adapted for WebApi
/// </summary>
/// <remarks>Reference: http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-%28csrf%29-attacks</remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
/// <summary>
/// Executes the authorization filter to synchronize.
/// </summary>
/// <param name="actionContext">The action context.</param>
/// <param name="cancellationToken">The cancellation token associated with the filter.</param>
/// <param name="continuation">The continuation.</param>
/// <returns>
/// The authorization filter to synchronize.
/// </returns>
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(
HttpActionContext actionContext,
CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
try
{
string cookieToken = string.Empty;
string formToken = string.Empty;
IEnumerable<string> tokenHeaders;
if (actionContext.Request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
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