Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing token in Flutter

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:

  • access token
  • access token lifetime
  • refresh token
  • refresh token lifetime

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.

like image 401
Bill Avatar asked Jun 21 '19 13:06

Bill


People also ask

How do I refresh my access token on flutter?

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 .

How do I refresh token?

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.

Is refresh token refreshed?

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.

Why do we need refresh token?

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.


1 Answers

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.

like image 73
Michael Werner Avatar answered Oct 12 '22 00:10

Michael Werner