Refreshing token in Flutter

8,526

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.

Share:
8,526
Bill
Author by

Bill

Updated on December 12, 2022

Comments

  • Bill
    Bill over 1 year

    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.

  • Bill
    Bill almost 5 years
    So by default Future.delayed will not execute if app is closed?
  • Michael Werner
    Michael Werner almost 5 years
    Yes. I suppose you think about starting a service when the device boot to run code in background as possible solution. (stackoverflow.com/a/10945530/11577024) I'm not sure that is possible without native code.
  • Michael Werner
    Michael Werner almost 5 years
    I have think about an alternative to your issue. You can also handling 401 http errors (token is expired), ask for a new token with the refresh token and try again your request. It consumes less battery and it also handles the case if the phone is off.
  • Bill
    Bill almost 5 years
    Great idea! Thank you, I will implement it this way.