Reputation: 22556
Can some one please show me how to integrateJWT into a default Web API project.
They just explain how to install the library using NuGet and how to generate tokens. But now how do I integrate it with an authentication based system?
My implementation so far:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Filters.Add(new **AuthFilterAttribute()**);
}
}
public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// In auth web method you should implement functionality of authentication
// so that client app could be able to get token
if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth"))
{
return;
}
// Receive token from the client. Here is the example when token is in header:
var token = **actionContext.Request.Headers["Token"];**
// Put your secret key into the configuration
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
try
{
string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);
}
catch (JWT.SignatureVerificationException)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}
Upvotes: 3
Views: 3551
Reputation: 44550
Implement TokenAuthenticationAttribute and register it globally:
Global.asax registration:
GlobalConfiguration.Configuration.Filters.Add(new TokenAuthenticationAttribute());
TokenAuthenticationAttribute:
public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
// In auth web method you should implement functionality of authentication
// so that client app could be able to get token
if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth"))
{
return;
}
// Receive token from the client. Here is the example when token is in header:
var token = actionContext.Request.Headers["Token"];
// Put your secret key into the configuration
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
try
{
string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);
}
catch (JWT.SignatureVerificationException)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}
Upvotes: 4