Skip to content

Instantly share code, notes, and snippets.

@wadewegner
Last active August 29, 2015 14:05
Show Gist options
  • Save wadewegner/790013f1b13b789f470c to your computer and use it in GitHub Desktop.
Save wadewegner/790013f1b13b789f470c to your computer and use it in GitHub Desktop.
TokenValidationHandler
public class TokenValidationHandler : DelegatingHandler
{
private readonly string _storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
const string errorMessage = "Unauthorized access; {0}";
const HttpStatusCode code = HttpStatusCode.Unauthorized;
var authValue = request.Headers.Authorization;
if (authValue == null)
return CreateErrorResponse(string.Format(errorMessage, "requires authorization header"), code);
if (String.IsNullOrWhiteSpace(authValue.Scheme))
return CreateErrorResponse(string.Format(errorMessage, "requires authorization scheme and parameter"), code);
if (authValue.Scheme != "Auth")
return CreateErrorResponse(string.Format(errorMessage, "invalid authorization scheme"), code);
if (String.IsNullOrWhiteSpace(authValue.Parameter))
return CreateErrorResponse(string.Format(errorMessage, "missing authorization parameter"), code);
var serverKey = authValue.Parameter;
var table = Storage.GetStorageTable(_storageConnectionString, "serverkey");
var query = new TableQuery<ServerKeyEntity>().Where(
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, serverKey));
var serverKeyEntity = table.ExecuteQuery(query).FirstOrDefault();
if (serverKeyEntity == null)
return CreateErrorResponse(string.Format(errorMessage, "invalid key"), code);
var userId = serverKeyEntity.RowKey;
request.Headers.Add("UserId", userId);
var response = await base.SendAsync(request, cancellationToken);
return response;
}
private static HttpResponseMessage CreateErrorResponse(string errorMessage, HttpStatusCode httpStatusCode)
{
return new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent(errorMessage)
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment