Skip to content

Instantly share code, notes, and snippets.

@r4hulp
Last active December 11, 2018 06:26
Show Gist options
  • Save r4hulp/162c25abe04d3190d95e80de948752f1 to your computer and use it in GitHub Desktop.
Save r4hulp/162c25abe04d3190d95e80de948752f1 to your computer and use it in GitHub Desktop.
Securing ASP.Net WebAPI, Gateway approach
CustomMessageHandler customMessageHandler = new CustomMessageHandler(){ InnerHandler = new HttpControllerHandler(config)};
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints : null,
handler : customMessageHandler
);
public class CustomMessageHandler: DelegatingHandler
{
protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) //Standard signature
{
const string tokenName = "Auth-Token";
if (request.Headers.Contains(tokenName)) //Check if request header contains auth token or not.
{
string requestToken= request.Headers.GetValues(tokenName).First(); //get the first of Auth token from request header
try
{
//VALIDATE THE TOKEN.. E.G. DECRYPT THE TOKEN AND CHECK IF THE USER IS VALID OR NOT
//I WILL BE SHARING EXAMPLE SNIPPET SOON ON MY GITHUB ON VARIOUS APPROACHES OF ACHIEVING SECURITY
//SUCH AS BASE64 ENCRYPTION, X.509 ENCRYPTION ETC.
if(//USER IS INVALID)
{
HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid username or password / identity.");
return Task.FromResult(reply);
}
}
catch (Exception ex) //token not found or invalid token
{
HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token.");
return Task.FromResult(reply);
}
}
else // IF REQUEST DOES NOT HAVE AUTHENTICATION TOKEN
{
HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Ooops, can not find token, make sure the requests have token.");
return Task.FromResult(reply);
}
return base.SendAsync(request, cancellationToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment