<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shivam Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Shivam Agrawal on Medium]]></description>
        <link>https://medium.com/@shiwal25?source=rss-dd59de71ed0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TOn3nWw4Iap52mVBm_G3SA.png</url>
            <title>Stories by Shivam Agrawal on Medium</title>
            <link>https://medium.com/@shiwal25?source=rss-dd59de71ed0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:08:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shiwal25/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Android auth architecture with encrypted tokens, auto-refresh, and reactive navigation]]></title>
            <link>https://proandroiddev.com/an-android-auth-architecture-with-encrypted-tokens-auto-refresh-and-reactive-navigation-b5dcb7704f83?source=rss-dd59de71ed0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5dcb7704f83</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Shivam Agrawal]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 06:29:53 GMT</pubDate>
            <atom:updated>2026-06-30T18:48:44.093Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Most “auth demo” store a token in SharedPreferences and call it done. It works, right up until you ask it three questions a real app can&#39;t avoid:</p><ul><li>What happens when the access token expires while a request is in flight?</li><li>What happens on cold start, when the stored token is already dead?</li><li>How does the UI know to jump to the home screen the instant login succeeds — from anywhere in the app, without an Activity restart?</li></ul><p>I kept hitting these questions while building <a href="https://github.com/shiwal25/android-secure-auth-architecture">android-secure-auth-architecture</a>, a reference implementation that treats auth as a reactive, encrypted data stream rather than a flag you check. It&#39;s built with <strong>Jetpack Compose, Ktor, Koin, and Google Tink</strong>, and this post walks through the four parts that made it click.</p><blockquote><em>⚠️ This is an architecture showcase, not a finished product. The backend is a separate service and isn’t included — </em><em>BASE_URL points at a placeholder. The point is to show how the pieces fit together, not to ship a drop-in library.</em></blockquote><p><a href="https://github.com/shiwal25/android-secure-auth-architecture">GitHub - shiwal25/android-secure-auth-architecture</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfLMxsmyltDV0bg2CBht5Q.png" /></figure><h4><strong>Dependencies</strong></h4><p>gradle/libs.versions.toml</p><pre>[versions]<br>koin = &quot;4.2.2&quot;<br>[libraries]<br>koin-android = { module = &quot;io.insert-koin:koin-android&quot;, version.ref = &quot;koin&quot; }<br>koin-androidx-compose = { module = &quot;io.insert-koin:koin-androidx-compose&quot;, version.ref = &quot;koin&quot; }</pre><p>gradle/build.gradle.kts</p><pre>//koin<br>    implementation(libs.koin.androidx.compose)<br>    implementation(libs.koin.android)<br>    implementation(platform(&quot;io.insert-koin:koin-bom:4.2.1&quot;))<br>    implementation(&quot;io.insert-koin:koin-android&quot;)<br>    implementation(&quot;io.insert-koin:koin-androidx-compose&quot;)<br>    implementation(&quot;io.insert-koin:koin-androidx-compose-navigation&quot;)<br><br>    //Jetpack Navigation<br>    implementation(&quot;androidx.navigation3:navigation3-ui:1.1.2&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-navigation3:2.10.0&quot;)<br><br>    //LifeCyle and ViewModel<br>    implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.10.0&quot;)<br>    implementation(&quot;androidx.lifecycle:lifecycle-runtime-compose:2.10.0&quot;)<br><br>    //Ktor<br>    implementation(platform(&quot;io.ktor:ktor-bom:3.5.0&quot;))<br>    implementation(&quot;io.ktor:ktor-client-android&quot;)<br>    implementation(&quot;io.ktor:ktor-client-content-negotiation&quot;)<br>    implementation(&quot;io.ktor:ktor-serialization-kotlinx-json&quot;)<br>    implementation(&quot;io.ktor:ktor-client-logging&quot;)<br>    implementation(&quot;io.ktor:ktor-client-auth&quot;)<br><br>    //Serialization<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0&quot;)<br><br>    //DataStore<br>    implementation(&quot;androidx.security:security-crypto:1.1.0&quot;)<br>    implementation(&quot;androidx.datastore:datastore:1.3.0-alpha09&quot;)<br>    implementation(&quot;androidx.datastore:datastore-tink:1.3.0-alpha07&quot;)<br>    implementation(&quot;com.google.crypto.tink:tink-android:1.21.0&quot;)<br><br>    //Coroutines<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0&quot;)</pre><h4><strong>Manifest</strong></h4><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br><br>    &lt;application<br>        android:name=&quot;.SecureAuthApplication&quot;<br>    ...&gt;<br>  &lt;/application&gt;</pre><h4><strong>Encrypted token storage</strong></h4><p>TokenDataStore wraps a DataStore&lt;AuthPreferences&gt; with an AeadSerializer from androidx.datastore.tink. The actual encryption key is an AES-256-GCM keyset managed by AndroidKeysetManager, wrapped by a key that never leaves the Android Keystore hardware-backed on most devices.</p><pre>val keysetHandle = AndroidKeysetManager.Builder()<br>    .withSharedPref(context, KEYSET_NAME, KEYSET_PREFS_NAME)<br>    .withKeyTemplate(KeyTemplate.createFrom(PredefinedAeadParameters.AES256_GCM))<br>    .withMasterKeyUri(MASTER_KEY_URI)<br>    .build()<br>    .keysetHandle<br><br>val aead: Aead = keysetHandle.getPrimitive(<br>    RegistryConfiguration.get(), Aead::class.java<br>)<br><br>val encryptedSerializer = AeadSerializer(<br>    aead = aead,<br>    wrappedSerializer = AuthPreferencesSerializer,<br>    associatedData = DATASTORE_FILE_NAME.encodeToByteArray()<br>)</pre><p>EncryptedSharedPreferencesis in maintenance mode and sits on top of the older, deprecated Security Crypto library. <strong>DataStore + Tink</strong> gets you the same Keystore backed AEAD encryption, but on DataStore&#39;s Flow-based, coroutine-native API which matters a lot once the rest of the app correctly treats auth state as a stream rather than a value you poll.</p><h4><strong>Reactive auth state</strong></h4><p>AuthViewModelcollects TokenDataStore.accessToken directly:</p><pre>private fun observeTokenForAuthState() {<br>    viewModelScope.launch {<br>        tokenDataStore.accessToken.collect { token -&gt;<br>            if (isFirstEmission) {<br>                isFirstEmission = false<br>                handleStartup(token)<br>            } else {<br>                _authState.value = if (token != null) {<br>                    AuthState.Authenticated<br>                } else {<br>                    AuthState.Unauthenticated<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Login, logout, and a silent mid-session refresh all produce the exact same effect: a new emission from the same Flow, picked up by the same collector. There&#39;s no separate &quot;now navigate to home&quot; call after login, saving the token to DataStore is the navigation trigger. That&#39;s the part of this design I&#39;m happiest with: it collapses three different &quot;the user&#39;s auth changed&quot; code paths into one.</p><p>The first emission is special-cased through handleStartup(), because cold start has a question the others don&#39;t: is the stored token still valid right now? JwtUtils decodes the JWT payload locally no network call and checks the exp claim with a 30-second buffer, so a request doesn&#39;t race a token that&#39;s about to expire mid-flight. If it&#39;s expired, the ViewModel triggers a refresh before deciding whether the user lands on the home screen or the login screen.</p><p>Root navigation just watches authState and swaps graphs — it has no opinions of its own about what &quot;logged in&quot; means:</p><pre>when (state) {<br>    AuthState.Loading         -&gt; SplashContent()<br>    AuthState.Unauthenticated -&gt; AuthNavGraph(authViewModel = authViewModel)<br>    AuthState.Authenticated   -&gt; MainNavGraph(authViewModel = authViewModel)<br>}</pre><h4><strong>Automatic refresh, via Ktor’s </strong><strong>Auth plugin</strong></h4><p>The interesting failure mode in any JWT app: an authenticated request goes out, the access token has just expired, and the request needs to transparently retry after a refresh, without every repository method knowing about refresh logic. Ktor’s Auth { bearer { ... } } provider handles exactly this.</p><pre>install(Auth) {<br>    bearer {<br>        loadTokens {<br>            // read current access + refresh token from DataStore<br>        }<br>        refreshTokens {<br>            val response = plainClient.post(refreshUrl) {<br>                setBody(RefreshRequest(refreshToken = storedRefreshToken))<br>            }<br>            when (response.status) {<br>                HttpStatusCode.OK -&gt; {<br>                    // save new tokens, return them as BearerTokens<br>                }<br>                HttpStatusCode.Unauthorized,<br>                HttpStatusCode.Forbidden -&gt; {<br>                    tokenDataStore.clearSession()<br>                    null<br>                }<br>                else -&gt; null<br>            }<br>        }<br>        sendWithoutRequest { request -&gt; request.url.host == BACKEND_HOST }<br>    }<br>}</pre><p>Three deliberate decisions live in here:</p><ul><li><strong>The refresh call uses the plain client, not the authenticated one.</strong> Otherwise a refresh request could itself trigger another refresh attempt and recurse.</li><li><strong>A 5xx during refresh doesn’t clear the session.</strong> Only a 401/403 — the server explicitly rejecting the refresh token — logs the user out. A transient server error just fails that one request; the user stays logged in and can retry.</li><li><strong>The 30-second expiry buffer mentioned earlier</strong> is what keeps this whole thing from racing the clock.</li></ul><h4><strong>Two HTTP clients</strong></h4><p>HttpClientFactory builds a plain client (no auth — used for /login, /register, /refresh) and a separate auth client (the Auth plugin installed — used for everything that requires a logged-in user). Koin wires these into the right repositories via named qualifiers, so it&#39;s structurally impossible to accidentally call an authenticated endpoint with a client that doesn&#39;t know how to refresh tokens. The DI graph itself enforces the boundary, instead of relying on a code review to catch it.</p><h4><strong>Trade-offs I made, and would reconsider at scale</strong></h4><ul><li><strong>Koin over Hilt</strong> : faster to iterate on during solo, early stage development; no codegen, and the runtime DI graph is easy to reason about at this project’s size. Hilt’s compile-time safety becomes more valuable as the module count grows.</li><li><strong>Navigation 3 over classic Navigation Compose</strong> : newer, and the API surface is still settling, but the NavKey-based back stack is a much more natural fit for type-safe, state-driven graph switching than string routes.</li><li><strong>Tink + DataStore over </strong><strong>EncryptedSharedPreferences</strong>: mainly about not building on a maintenance-mode API.</li><li><strong>Result&lt;Unit&gt; over throwing exceptions across the repository boundary</strong> : every AuthRepository method returns a Result&lt;Unit&gt; with a human-readable failure message, so the ViewModel never has to catch anything, it just pattern-matches on success or failure.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5dcb7704f83" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/an-android-auth-architecture-with-encrypted-tokens-auto-refresh-and-reactive-navigation-b5dcb7704f83">An Android auth architecture with encrypted tokens, auto-refresh, and reactive navigation</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>