Reputation: 1117
Has any library for react native that handle token refresh? Or I need to do a schedule for refresh the token? if yes, iOS permitt the schedule execute in background? or I can check every server response if the token is valid if not refresh it?
What is the best way to implement this?
Upvotes: 4
Views: 2915
Reputation: 664
When I faced this problem, I thought of two strategies to handle token refresh with your API:
Your server should send a INVALID_TOKEN_ERROR
moment at which you could make your own refreshToken(credentials)
.
One technique that I find interesting to hook there would be to polyfill fetch
in a similar way as in this article:
Handling Failed HTTP Responses With fetch()
What I do at the moment on my app is to refresh my token at app start, regardless of the token's time to live. So unless your user keeps the app opened for a time longer than your time to live, you should not encounter any issue.
I hook at app start using redux-persist loaded state callback.
The refresh token function is quite simple if you use fbsdk
:
import { AccessToken } from 'react-native-fbsdk'
[...]
AccessToken.refreshCurrentAccessTokenAsync()
.then((FBTokenObject) => {
let FBToken = FBTokenObject.accessToken
[refresh your own API token using FBToken]
)
If you use an email and password strategy, you should look into react-native-keychain, to save the credentials on the device in a secure way.
I did not implement the token refresh on API error because my token's time to live is of 5 days and I think the second strategy is good enough at the moment. But I definitely would if my token's time to live was shorter than 2 days.
You can also improve performance by checking your time to live and decide, depending on the value, if you want to refresh the token or not, but, in my opinion, that's not so much of a gain.
Upvotes: 5