3

Can some one please show me how to integrateJWT into a default Web API project.

Here is the library

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);
        }
    }
}

1 Answer 1

4

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);
        }    
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Could you possibly also add a code block with an example of how to use the token? Ie how do I use it? do i just put a [Authorize] above the controller?
@Zapnologica as far as you are registering it globally, your attr will be executed for every request. No need to put attr above every controller. You only have to allow anonymous access to methods like Authenticate etc.
Ok great. That sounds Ideal. I will give it a try and get back to you. With your example I obviously have to still install it using nuget. then configure it in the global.asax file. Where do I put the TokenAuthenticationAttribute: code?
@Zapnologica anywhere you like. Create folder "Attributes" in you project ;)
@Zapnologica what the errors? compilation time/runtime?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.