Search code examples
c#asp.netasp.net-web-api2jwtmiddleware

How can I avoid boilerplate code to validate JWT Token in ASP.NET Web API 2?


All my REST API methods start with that code as follows:

[HttpPost]
[Route("Login")]
public async Task<IHttpActionResult> Login(QueryModel q)
{
    // get JWT Token string form HTTP Header
    string token = Request.Headers.GetValues("Authorization").FirstOrDefault();

    // decode token
    string json = Jose.JWT.Decode(token, JWTModel.secretForAccessToken);
    JWTModel jwt = JsonConvert.DeserializeObject<JWTModel>(json);

    // check if issued from my homepage.
    if (!jwt.iss.Equals("my-home-page.com"))
    {
        return Content(
            HttpStatusCode.Unauthorized, 
            "access token is not from here"
        );
    }
    // check if it has valid about time
    long now = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
    if (jwt.iat > now || jwt.exp < now)
    {
        // request refresh token
        return Content(
            HttpStatusCode.Unauthorized, 
            "outdated access token"
        );
    }
    /* ... */
}

How ridiculous and redundant are they!

Can I simplify and modulize them? And How?

(In Node.js, I can solve it by using so called middleware.)


Solution

  • I would suggest you look at DelegatingHandler or if you are running an OWIN based application then you can create Middleware

    DelegatingHandler MSDN Link

    OWIN Middleware MSDN