简体   繁体   中英

WebAPI token on Header - how to set 30 minutes expiration

Let's assume I have a WebAPI that returns a Security Token (a GUID) on the Header of a Login call.

Ideally we would like to receive further calls within the 30 minutes and every time we receive a call, we need to change the token to get another 30 minutes.

Constraint: I cannot use the Session.

What's the right way to set an expiration on a specific Header value on a WebAPI environment?

Instead of sending a GUID, you can change your token to structured data. For example: JWT

The general steps to generate a token are:

  1. Create a structured data includes {id: GUID, exp: time}
  2. Serialize it to a string (JSON.net)
  3. Encrypt the data (Machine key / Dpapi encryption)
  4. Encode the data (Base64)

The steps to receive a token are just reverse the steps above.

After you get the expiration time on server code, you can determine if you need to refresh the token or not. That procedure above is actually what cookie authentication does in ASP.NET.

For token header based auth, it's better to follow OAuth 2.0 spec to use refresh token to extend the token expiration time.

BTW, Owin OAuth middleware already supports oauth bearer token. I have a blog about how it works in SPA template. You may consider using that instead of inventing your own. Thanks.

[Update] I just uploaded another sample project which simplifies the bearer token authentication without following OAuth 2.0 flow.

I don't think that you have selected a right solution/Approach. It is a consumer job to get token refreshed in a proper time(as soon as a token gets expired) I would suggest to build a separate STS Service that issues tokens to consumers and then this token is sent to the web API web Service(in headers). Web API Service verifies that token was signed with the proper secret key and if it is the case then allows to get the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM