Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Handling Periodic token refresh using WorkManager

Handling Periodic token refresh using WorkManager

Most mobile apps use token-based authentication as a security technique to authenticates the users who attempt to log in to a server through the app.

Every user token has an expiration period(this is defined by the backend auth system), therefore the user cannot access the server with an expired token.

In this talk, I share how to use WorkManager to handle periodic background tasks, in this case, token refresh.

WorkManager is an Android library that runs deferrable background work when the work’s constraints are satisfied.

Nsikak Thompson

June 25, 2020
Tweet

More Decks by Nsikak Thompson

Other Decks in Programming

Transcript

  1. 2019 | Confidential and Proprietary GDG Location About me •

    I am mobile developer currently leading mobile teams at StarthubTech & AltaLabs. • Co-lead GDG Uyo • A beginner Flutter Developer
  2. GDG Location Most mobile apps use token based authentication as

    a security technique to authenticates the users who attempt to log in to a server through the app.
  3. GDG Minna Every user token has an expiration period(this is

    defined by the backend auth system), therefore the user cannot access the server with an expired token
  4. 2019 | Confidential and Proprietary GDG Location Scope What is

    WorkManager? Setup WorkManager Create a WorkRequest Schedule token update Check for expired token at app launch or Resume
  5. GDG Location WorkManager is an Android library that runs deferrable

    background work when the work’s constraints are satisfied. WorkManager is an API part of the Android Jetpack Library. - Work constraints - Task scheduling - Work Chain What is WorkManager
  6. GDG Location Worker Class - Work is defined using the

    Worker class. The doWork() method is run synchronously on a background thread provided by WorkManager. WorkManager Concepts Results - This is the status of work returned by the doWork() method. • Result.success(): The work finished successfully. • Result.failure(): The work failed. • Result.retry(): The work failed and should be tried at another time according to its retry policy.
  7. GDG Location WorkRequest - define how and when it should

    be run. 1. OneTimeWorkRequest 2. PeriodicWorkRequest WorkManager Concepts
  8. GDG Location First time Login Process Login The user’s token

    is required to make request to the server in most case. Make Other HTTP Request This is saved locally using Database or SharedPreference. Also the login time. It return the users information which include the token and refresh Token. This token expires after 60 mins Login Successful Email and Password Save User details 1 2 3 4
  9. GDG Location Add these dependencies to your build.gradle file Set

    up WorkManager dependencies { def work_version = "2.1.0" // (Java only) implementation "androidx.work:work-runtime:$work_version" // Kotlin + coroutines implementation "androidx.work:work-runtime-ktx:$work_version" } https://developer.android.com/jetpack/androidx/releases/work
  10. GDG Location Create a class that will extend the Worker

    class passing in context and the workerParams. Create Token Worker class TokenWorker constructor(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) { override fun doWork(): Result { //Handle your work here return result!! } }
  11. GDG Location Add the logic to perform the token refresh

    in the doWork() method. Add Refresh Token work override fun doWork(): Result { AndroidWorkerInjection.inject(this) if (preferenceHelper.isLoggedIn) { disposable = appCache.getUserInfo() //call the api to refresh the token .flatMapCompletable {userDataStore.refreshToken( RefreshToken.Params(it.email, it.refreshToken))} .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())
  12. GDG Location The Result returned from doWork() informs WorkManager whether

    the task: - finished successfully via Result.success() - failed via Result.failure() Subscribe for Results ……. .subscribe ({ result = Result.success() Timber.e("Token refresh was successful") }, {error -> result = Result.failure() Timber.e("Token refresh failed") }) } return result!! }
  13. GDG Location Using PeriodicWorkRequest to schedule the token refresh task

    to run after every 50 minutes. Remember the token validity period is 60 minutes, so we are trying to update the token before it actually expires. This helps us keep our user covered Create WorkRequest fun startTokenRefreshPeriodicWork() { val tokenRefreshBuilder = PeriodicWorkRequest.Builder( TokenWorker::class.java, 50, TimeUnit.MINUTES )
  14. GDG Location The work is also given constraints that tells

    the work to only execute the device is connected to a Network. Add Constraints //This defines the job constraints. val tokenRefreshConstraint = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val tokenRefreshWork = tokenRefreshBuilder .addTag("TOKEN_REFRESH") .setConstraints(tokenRefreshConstraint) .build() }
  15. GDG Location Once the user login is successful, the WorkManager

    will schedule the job. Schedule token update WorkManager.getInstance().enqueue(tokenRefreshWork)
  16. GDG Location Token refresh for already Logged in user Request

    Token refresh The new active token will be available for the user Make HTTP Request The server returns a new token and a refresh token Request Successful The workmanager request for the a new token at the scheduled time Update Local storage 1 2 3 4