如何避免样板代码验证ASP.NET Web API 2中的JWT令牌?

时间:2017-08-10 02:34:19

标签: c# asp.net asp.net-web-api2 jwt middleware

我的所有REST API方法都以该代码开头,如下所示:

[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"
        );
    }
    /* ... */
}

他们多么荒谬和多余!

我可以简化和模块化吗?怎么样?

(在Node.js中,我可以通过使用所谓的中间件来解决它。)

1 个答案:

答案 0 :(得分:0)

我建议您查看DelegatingHandler或者如果您运行的是基于OWIN的应用程序,那么您可以创建中间件

DelegatingHandler MSDN Link

OWIN Middleware MSDN