6

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
  • 507
  • 1
  • 5
  • 11

1 Answers1

2

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.

  • So by default `Future.delayed` will not execute if app is closed? – Bill Jun 21 '19 at 14:43
  • Yes. I suppose you think about starting a service when the device boot to run code in background as possible solution. (https://stackoverflow.com/a/10945530/11577024) I'm not sure that is possible without native code. – Michael Werner Jun 21 '19 at 18:29
  • 7
    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. – Michael Werner Jun 21 '19 at 18:50
  • 1
    Great idea! Thank you, I will implement it this way. – Bill Jun 22 '19 at 08:40