DEV Community

Charles Etieve
Charles Etieve

Posted on

Store JWT Token with Coroutines

JWT (JSON Web Token) has become a popular standard for implementing stateless authentication in modern mobile apps. In order to maintain security and avoid session hijacking, it's important to store JWT tokens securely on the client-side.

DataStore is a popular choice for storing tokens as it provides the advantages of shared preferences along with additional coroutines capabilities:

// store token (must be called from suspend function)
dataStore.edit { it[KEY_TOKEN] = token }
// read token (returns a flow of token) { it[KEY_TOKEN] }
Enter fullscreen mode Exit fullscreen mode

One powerful use case is to navigate to the home or login view on wether the token exists or not:
        .map { it.contains(KEY_TOKEN) }
        .onEach { isAuthenticated ->
                when(isAuthenticated) {
                        true -> navController.navigate("home")
                        false -> navController.navigate("login")
Enter fullscreen mode Exit fullscreen mode

However DataStore lacks support for encryption, whereas shared preferences does. This means developers have to choose between the convenience of coroutines and the security of encryption when choosing a method to store their JWT tokens.

Meme about adroid developer choosing between coroutines and encryption for JWT Token

Fortunately, there is a library Encrypted DataStore that extends DataStore and allows for easy encryption. While this solution is currently useful, it may become deprecated in the future once DataStore natively implements this functionality.

Enough talk, let's dive into the code.

First, import libraries in your build.gradle (app module):

// datastore
// extension for datastore to support encryption
// utility library for datastore encryption
Enter fullscreen mode Exit fullscreen mode

Then you will need to build your datastore to inject it in your AuthenticationService:

val dataStore = PreferenceDataStoreFactory.createEncrypted{
      // the file should have extension .preferences_pb
Enter fullscreen mode Exit fullscreen mode

Finally you can add this service to your project:

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull

class AuthenticationService(
    private val dataStore: DataStore<Preferences>
) {

        // returns a flow of is authenticated state
    fun isAuthenticated(): Flow<Boolean> {
                // flow of token existence from dataStore
        return {

        // store new token after sign in or token refresh
    suspend fun store(token: String) {
                // store token to dataStore
        dataStore.edit {
            it[KEY_TOKEN] = token

        // get token for protected API method
    suspend fun getToken(): String {
                  .map { it[KEY_TOKEN] } // get a flow of token from dataStore
          .firstOrNull() // transform flow to suspend
              ?: throw IllegalArgumentException("no token stored")

        // to call when user logs out or when refreshing the token has failed
    suspend fun onLogout() {
                // remove token from dataStore
        dataStore.edit {

    companion object {
        val KEY_TOKEN = stringPreferencesKey("key_token")
Enter fullscreen mode Exit fullscreen mode

In conclusion, there is now an efficient and secure data storage option available for your JWT tokens, so there's no excuse to settle for anything less! 😊

Top comments (0)