I am developing a Flutter application and I am using OAuth2 for authentication. The application can't be used if you are not logged in, it just shows a login screen and forces you to log in.
When I log in, I receive the following information from the authentication server:
When the access token is about to expire, I want to get a new one by sending refresh token to authentication server.
How would I implement the refresh token mechanism? I want to update the access token every time before it expires, even if user is not using the application (it is closed). If user needed to log in every time he opens the application, it would be very bad user experience. To avoid this, I want to refresh the token in background.
How can I achieve this to work on Android and iOS? Preferably without writing any native code for each of the platforms.
In order to store our refresh token securely in the app, install Flutter Secure Storage by running in the terminal: flutter pub add flutter_secure_storage . Inside the constructor of Api is where we can add the access token to every request using interceptors with dio. Api() { api. interceptors .
To get a refresh token , you must include the offline_access scope when you initiate an authentication request through the /authorize endpoint. Be sure to initiate Offline Access in your API. For more information, read API Settings.
A refresh token just helps you re-validate a user without them having to re-enter their login credentials multiple times. The access token is re-issued, provided the refresh token is a valid one requesting permission to access confidential resources.
Refresh tokens help improve the user experience (UX) around authentication. Since access tokens are typically only valid for a few minutes, an expired token can cause a user session to terminate without warning. Once that token expires, the user needs to reauthenticate to receive a new token and a new session.
You can use Future.delayed
to refresh the token before the expiration.
You can also run this part of code in background with background processes but your application must be in background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With