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的,我可以用所謂的中間件解決這個問題。)
我不使用OWIN,但DelegatingHandler看起來很爽。我將立即將其應用於我的代碼!我會報告結果。 –
我終於實現了使用'DelegatingHandler'清理我的代碼! [此文檔](https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers#example-checking-for-an-api-key)也有幫助。 –