protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string token; HttpResponseMessage errorResponse = null; if (TryRetrieveToken(request, out token)) { try { string secret = SymmetricKey.Replace('-', '+').Replace('_', '/'); Thread.CurrentPrincipal = JsonWebToken.ValidateToken( token, secret, Audience, true, Issuer); if (HttpContext.Current != null) { HttpContext.Current.User = Thread.CurrentPrincipal; } } catch (SignatureVerificationException ex) { errorResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex); } catch (JsonWebToken.TokenValidationException ex) { errorResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex); } catch (Exception ex) { errorResponse = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } return(errorResponse != null? Task.FromResult(errorResponse) : base.SendAsync(request, cancellationToken)); }