Created
August 4, 2015 15:44
-
-
Save hanssens/b38ba7ff2079ef5effc9 to your computer and use it in GitHub Desktop.
RequireSessionKeyAttribute - Authenticates a token provided as a a header in a webapi request.
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
/// <summary> | |
/// Authenticates a token provided as a a header in a webapi request. | |
/// </summary> | |
public class RequireSessionKeyAttribute : ActionFilterAttribute | |
{ | |
public string TokenFieldName { get; set; } | |
public RequireSessionKey() : this("token") { } | |
public RequireSessionKey(string tokenFieldName) | |
{ | |
this.TokenFieldName = tokenFieldName; | |
} | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
// check if a header is available | |
if (actionContext.Request.Headers.All(x => x.Key != TokenFieldName)) | |
{ | |
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); | |
} | |
else | |
{ | |
// fetch the token | |
var headers = actionContext.Request.Headers.GetValues(TokenFieldName); | |
var authToken = headers.FirstOrDefault(); | |
if (!IsValidToken(authToken)) | |
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); | |
} | |
// finish executing the action | |
base.OnActionExecuting(actionContext); | |
} | |
protected bool IsValidToken(string token) | |
{ | |
if (string.IsNullOrEmpty(token)) return false; | |
// TODO: Validate token here | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment