简体   繁体   中英

Protecting REST web services using OAuth2: General principles

We are building a RESTful web application in java using Spring security and OAuth2.

Everything is working as expected and I'm starting to understand the basics of access and refresh tokens, but there are still some inclarities and by browsing the internet, I get even more confused by different viewpoints.

The way our implementation works right now:

In spring-security we can only have 1 valid refresh token for a given user at a time. We have a validity period for refresh tokens of 300 seconds (5 minutes). Every time we ask a new refresh token for the user, the same refresh token is returned but the validity time is not reset.

That way, a new refresh token is asked in the background every 302 seconds and this refresh token is used to request the access tokens that are put in the authorization headers of the REST calls.

This works ok most of the time, but if requests are executed in between the 300 and 302 seconds where the first refresh token is expired and the second not yet returned, we get an authentication error and the user is logged out of the application.

I read a lot of different advice on the internet:

  • The first one is to request a new refresh token for every web service call. This one we didn't consider since we have to provide the credentials (username/password) to obtain the refresh token for every single WS request.

  • Second one is to increase the validity period of a refresh token to 10 hours (instead of 5 minutes). This would solve or problem for most of the cases. But there is still the chance the user is logged out after the expiration time of the refresh token and before he has a new one.

What is the best approach to solve this issue. Is a validity time of 10 hours safe? Is it recommended to use a new refresh token for every single ws call?

I think it isn't really good practice to create new refresh tokens for every call. The whole point of refresh token is to get new Access Token when it expires. So when you get the authentication error (assuming 401) you know that the Access Token is expired or it is not valid anymore, then you should try to refresh it with refresh token to get new Access Token. If the Access Token refreshing doesn't work then the user should be logged out. In every refreshed Access Token response you can assign a new refresh token, so as long as the user have valid refresh token he/she can get new Access Token when it expires.

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