2017-08-10 19 views
1

我所有的REST API方法開始與該代碼如下:如何避免使用樣板代碼驗證ASP.NET Web API 2中的JWT令牌?

[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的,我可以用所謂的中間件解決這個問題。)

回答

0

我建議你看看DelegatingHandler,或者如果您運行的是基於OWIN應用程序,那麼你可以創建中間件

DelegatingHandler MSDN Link

OWIN Middleware MSDN

+0

我不使用OWIN,但DelegatingHandler看起來很爽。我將立即將其應用於我的代碼!我會報告結果。 –

+0

我終於實現了使用'DelegatingHandler'清理我的代碼! [此文檔](https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers#example-checking-for-an-api-key)也有幫助。 –