Created
January 31, 2014 09:40
-
-
Save feanz/86fa21a0cea1310315e8 to your computer and use it in GitHub Desktop.
Validate AntiForgery Token Attribute that could be used for web api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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