Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created August 4, 2015 15:44
Show Gist options
  • Save hanssens/b38ba7ff2079ef5effc9 to your computer and use it in GitHub Desktop.
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.
/// <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