<?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 Maxim  Myalkin on Medium]]></title>
        <description><![CDATA[Stories by Maxim  Myalkin on Medium]]></description>
        <link>https://medium.com/@maximmyalkin?source=rss-23be660aa73e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v8bz2lek1zYMVRmgNZizlg.png</url>
            <title>Stories by Maxim  Myalkin on Medium</title>
            <link>https://medium.com/@maximmyalkin?source=rss-23be660aa73e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:21:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maximmyalkin/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[KMM Through iOS Developer’s Eyes]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50?source=rss-23be660aa73e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c23cded1a50</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmp]]></category>
            <dc:creator><![CDATA[Maxim  Myalkin]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 14:06:51 GMT</pubDate>
            <atom:updated>2025-04-02T07:22:43.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDW5mPFl-qFbYK-_hxdYUA.png" /></figure><p>Hi! My name is Maxim Myalkin, I’m mobile teamlead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>We use Kotlin Multiplatform Mobile (KMM) to share code across Android and iOS.</p><p>You can find a fair number of articles on this technology, but most of them are either about choosing a cross-platform technology or about a project transition to KMM.</p><p>I’d like to talk about our experience with KMM from the iOS development perspective. We’ll discuss the problems we encountered and their solutions, our development approach, and, most importantly, how iOS devs feel about this technology.</p><p><em>Content:</em></p><ul><li><strong>Context</strong></li><li><strong>Kotlin</strong></li><li><strong>Environment</strong></li><li><strong>Nuances with the use of KMM<br></strong> -Linking common code to an iOS project<br>- Where to store common code?<br>- Coroutines, Flow<br>- Native libraries in common<br>- Common libraries in native</li><li><strong>Implementing specific areas of the project<br>- </strong>DI<br>- Navigation<br>- Network<br>- UI</li><li><strong>Debugging an app</strong></li><li><strong>Crashes</strong></li><li><strong>Logging non-critical errors</strong></li><li><strong>Memory leaks</strong></li><li><strong>Process</strong></li><li><strong>Bottom line</strong></li></ul><h3>Context</h3><p><a href="https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html">Kotlin Multiplatform Mobile</a> (KMM) is an SDK for multiplatform development from JetBrains. It allows you to bring reusable business logic into a module that is shared between iOS and Android platforms.</p><p>KMM’s alpha version was released in August 2020. The technology went into<a href="https://blog.jetbrains.com/kotlin/2022/10/kmm-beta/"> beta</a>. At the same time, Google <a href="https://android-developers.googleblog.com/2022/10/announcing-experimental-preview-of-jetpack-multiplatform-libraries.html">began migrating</a> Jetpack libraries to KMM.</p><p>Now we see that large companies use KMM in mobile apps more and more frequently. The examples are:</p><ul><li>QIWI</li><li>Profi</li><li>Leroy Merlin</li><li>AliExpress</li><li><a href="https://touchlab.co/kamp-kit-touchlab/">Touchlab</a></li><li><a href="https://medium.com/mcdonalds-technical-blog/mobile-multiplatform-development-at-mcdonalds-3b72c8d44ebc">McDonald’s</a></li></ul><p>Our team uses KMM to optimize the development and maintain existing code, which is especially important on projects with deadlines. I will not dive deep into why we’ve chosen it, but in short: KMM made it possible not to retrain our team, as it would have been if we had used Flutter.</p><p>Business logic and data handling are usually the same for Android and iOS. And KMM allows you to write code for two platforms at once and still keep the implementation of the UI native.</p><p>We put all platform-independent logic into the KMM module:</p><ul><li>network requests</li><li>data parsing</li><li>data storage</li><li>business logic: checking authorization, validation of entered data, changing the state of screens. We have business logic as an MVI feature written using MVIKoltin</li></ul><p>You can check out what other companies transfer to the cross-platform part in the <a href="https://blog.jetbrains.com/kotlin/2021/10/multiplatform-survey-q1-q2-2021/">JetBrains survey results</a>.</p><p>Using KMM does not change the Android development in any way, except for the networking and storage libraries part. Multi-module projects have already become a default in Android development. And the business logic is written in Kotlin without any platform dependencies and according to the clean architecture.</p><p>Still, there are nuances to implementing KMM in iOS development. We’ll talk about them later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YIN5uDg-75VVnfYi60OwQ.jpeg" /></figure><p>Not always iOS developers implement the KMM’s general functionality. But in our team we have not only Android, but also iOS developers who do it.</p><p>The first problem an iOS developer faces is a new language. Most of them have never worked with Kotlin. They work with Swift. In our team and according to feedback from other companies, iOS developers have had no difficulties understanding the Kotlin code. Kotlin and Swift are both modern and evolving programming languages, and there are many similarities between them.</p><p>What was unusual in the beginning:</p><ul><li>you cannot use the same method or class names within the same package, even if they are declared in different parts: common, iOS</li><li>expression chain and <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a> are hard to read and use</li></ul><p>There are also nuances lurking at the Swift–Kotlin interop stage. Kotlin/JVM is used for Android and Kotlin/Native is used for iOS.</p><p>In most cases, these nuances are insignificant:</p><ul><li>unlike Swift, Kotlin has no checked exceptions. If the method throws an exception, the iOS part will crash. To avoid this, the method declaration must be annotated with <a href="https://habr.com/users/Throws">@Throws</a> (Exception::class). But we adhere to the approach where the Result wrapper is returned. That is, the method returns either success or fail, and no exception is ever thrown</li><li>extensions in Kotlin are <a href="https://kotlinlang.org/docs/native-objc-interop.html#extensions-and-category-members">not converted</a> into Swift extensions in most cases</li><li>sometimes Kotlin internal classes are converted into Swift internal classes, and sometimes not</li><li>no support for generic protocol, generic func. This is quite an important point when working with Kotlin Flow.</li><li>no support for default arguments in Swift</li><li>no support of sealed class in Swift</li></ul><p>Some of these nuances can be fixed with the <a href="https://github.com/icerockdev/moko-kswift">gradle plugin</a>, which will generate a more suitable Swift code. For improved support of coroutines and Flow in Swift, you can use this <a href="https://github.com/rickclephas/KMP-NativeCoroutines">library</a>.</p><p>You can find a list of interop nuances in <a href="https://kotlinlang.org/docs/native-objc-interop.html">an article from JetBrains</a>. There is also a <a href="https://github.com/hhru/kotlin-swift-interopedia">repository</a> with a detailed description and explanation of all the nuances of interop and usecases.</p><p>What causes problems:</p><ul><li>Take caution when upgrading the Kotlin version and test the entire app. We had dependency conflicts that caused crashes in iOS and Android runtime.</li><li>Mind the nuances of working with memory in a multi-threaded environment in Kotlin Native. Objects should be immutable when transferred between threads. This problem occurs almost immediately when you try to display data from the server on the screen (although you don’t mutate it) when using the ktor + kotlinx.serialization bundle. There is an <a href="https://github.com/Kotlin/kotlinx.serialization/issues/1450">issue</a> on Github with a hack to work around this problem.</li></ul><p>Now, with the release <a href="https://blog.jetbrains.com/kotlin/2021/08/try-the-new-kotlin-native-memory-manager-development-preview/">of the new memory model</a>, the immutability problems are fading away. It is enabled <a href="https://kotlinlang.org/docs/whatsnew1720.html#the-new-kotlin-native-memory-manager-enabled-by-default">by default</a> since version 1.7.20. Objects can now be accessed from any threads and the tracing garbage collector is used.</p><p>It is important to understand that there can be problems because the technology is not in the release state. The release is <a href="https://youtrack.jetbrains.com/issue/KT-55513">planned</a> for late 2023.</p><h3>Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZxBOxsqNWfz9LzVJUPNNA.jpeg" /></figure><p>We currently use two environments to work with KMM and iOS: Android Studio and Xcode.</p><p>Android Studio alone is not enough for development: it does not allow you to work properly with the iOS code. Syntax highlighting, compiling, and app launching work (you can see how this works under the hood in <a href="https://www.youtube.com/watch?v=2YZnpTLsrQ4">an interview</a> with the KMM plugin developer), but the navigation, hints, and usage search do not. It is generally a pleasure for an iOS developer to use Android Studio: it is convenient to debug and work with Git and the terminal there. But it is quite demanding on resources.</p><p>Due to the limitations of the Android Studio, a developer needs to keep two IDEs open: Android Studio and Xcode. And this increases the developer’s hardware level requirements. At the same time, the Gradle build system consumes a lot of memory. But with 16Gb of RAM you can comfortably use 2 IDEs at once: Xcode and Android Studio in small projects.</p><p><strong>Screenshots of two systems used on different machines:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*le86fyneWaWNwlsXvFJ1PQ.png" /><figcaption>16 Gb</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTc-nch5TM-uGhSwwRiAoA.png" /><figcaption>32Gb</figcaption></figure><p>To solve this issue, we tried AppCode instead of two IDEs. Everything’s out of the box there, and it’s easy to understand if you’ve dealt with Android Studio before. On the other hand, this solution is paid and, unfortunately, JetBrains recently <a href="https://blog.jetbrains.com/appcode/2022/12/appcode-2022-3-release-and-end-of-sales-and-support/">announced</a> that they discontinue developing it.</p><p>For today, we see the parallel use of Xcode and Android Studio as an optimal solution, if the resources of your machine allow it.</p><p>To make sure that all necessary software is available on the developer’s machine, use <a href="https://github.com/Kotlin/kdoctor">KDoctor</a>.</p><p>We have encountered problems assembling the KMM part on Mac systems with Apple Silicon. The solutions from this <a href="https://betterprogramming.pub/some-errors-ive-found-developing-with-kmm-d7480161f15d">article</a> helped us solve the issue. Initially we worked with Rosetta, which increased the build time, but since Kotlin 1.5.30 Apple Silicon chips are supported.</p><h3>Nuances with the use of KMM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMzQbkFVdL2XGVAxkQeoxg.jpeg" /></figure><h4>Linking common code to an iOS project</h4><p>When you work with KMM in iOS you immediately face a question: how to connect a module with a common code to a project?</p><p>Currently there are two ways to do it:</p><ul><li>Cocoapods</li><li>Regular framework</li></ul><p>When using the regular framework in an iOS project, a script call is added before the build:</p><pre>cd &quot;$SRCROOT/..&quot;<br>./gradlew :shared:embedAndSignAppleFrameworkForXcode</pre><p>Later, <a href="https://kotlinlang.org/docs/native-cocoapods.html#add-and-configure-kotlin-cocoapods-gradle-plugin">the integration with CocoaPods</a> came out and we started using it (we use this dependency manager on iOS). That helped us to get rid of unnecessary steps.</p><p>Under the hood, the plugin automatically generates a podspec file for the shared library.</p><p>A script phase is added inside the podspec. It allows you to build a shared module every time you build an iOS app and see all changes.</p><p><strong>shared.podspec</strong></p><pre>spec.script_phases = [<br>   {<br>       :name =&gt; &#39;Build shared&#39;,<br>       :execution_position =&gt; :before_compile,<br>       :shell_path =&gt; &#39;/bin/sh&#39;,<br>       :script =&gt; &lt;&lt;-SCRIPT<br>           if [ &quot;YES&quot; = &quot;$COCOAPODS_SKIP_KOTLIN_BUILD&quot; ]; then<br>             echo &quot;Skipping Gradle build task invocation due to COCOAPODS_SKIP_KOTLIN_BUILD environment variable set to \&quot;YES\&quot;&quot;<br>             exit 0<br>           fi<br>           set -ev<br>           REPO_ROOT=&quot;$PODS_TARGET_SRCROOT&quot;<br>           &quot;$REPO_ROOT/../gradlew&quot; -p &quot;$REPO_ROOT&quot; $KOTLIN_PROJECT_PATH:syncFramework \<br>               -Pkotlin.native.cocoapods.platform=$PLATFORM_NAME \<br>               -Pkotlin.native.cocoapods.archs=&quot;$ARCHS&quot; \<br>               -Pkotlin.native.cocoapods.configuration=&quot;$CONFIGURATION&quot;<br>       SCRIPT<br>   }<br>]</pre><p>Let’s note that now you don’t need to configure anything manually to communicate the shared part with the iOS part. When you create a project, everything is already set up and works okay.</p><p><a href="https://blog.jetbrains.com/kotlin/2021/07/multiplatform-gradle-plugin-improved-for-connecting-kmm-modules/">Previously</a>, manual tuning was required. And there were cases where an iOS project would not build because it could not see the new changes in the shared module.</p><h4>Where to store common code?</h4><p>In a project, you can also use a monorepo for cross-platform and native code…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqJHiXRa7waa73sdXGRgfw.jpeg" /></figure><p>…or distribute the cross-platform part independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-1n2_mcRfsEMgRqypCQTA.jpeg" /></figure><p>We use a monorepo which allows different developers (both iOS and Android) to write cross-platform code and immediately integrate changes into the native part without intermediate publication of the artifact.</p><h4>Coroutines, Flow</h4><p>An iOS developer can figure out how to use coroutines in Kotlin fairly quickly. Swift 5.5 added an asynchronous approach with async-await and <a href="https://www.wwdcnotes.com/notes/wwdc21/10134/">structured concurrency</a>. This makes asynchrony in Swift and Kotlin similar. That is, an iOS developer can easily write asynchronous code in the shared part, especially if the project is already set up and the approaches to code writing are defined.</p><p>The nuances arise at the Kotlin–Swift interop stage. The default suspend method call in Kotlin turns into a completionHandler in Swift.</p><p>You also need to put the <a href="https://habr.com/users/Throws">@Throws</a> annotation to the suspend methods to alert Swift of a possible error, because Kotlin has no checked exceptions. Without the annotation, if an error occurs in the suspend method, the app crashes.</p><p>In addition to completionHandler, you can use async-await syntax for suspend methods. This feature is currently experimental and has structured-concurrency <a href="https://youtrack.jetbrains.com/issue/KT-47610">limitations</a>.</p><p>Both completionHandler and async-await do not support coroutines cancellation. <a href="https://github.com/rickclephas/KMP-NativeCoroutines">KMP-NativeCoroutines</a> allows to fix this shortcoming.</p><p>We don’t call suspend methods from Swift in our projects because the interaction with the shared is limited to the MVI-Store interface, where we drop the intents and observe the change of the screen state. Like via a callback. And all the work with asynchrony happens inside MVI, only in the Kotlin part.</p><h4>A brief Implementation of MVI</h4><pre>// ios common<br>class MviComponent {<br>    …<br>    fun onStart() {<br>        binder = bind(mainContext = Dispatchers.Main.immediate) {<br>            store.states bindTo ::acceptState<br>        }<br>    }<br><br>    private fun acceptState(state: StateType) {<br>        mviView.render(state)<br>    }<br>}</pre><pre>// ios native<br>final class FeatureView: MviView {<br>    override func render(model: ClaimDetailsStoreState) {<br>      // sending value в VC    <br>    }<br>}</pre><h4>Native libraries in common</h4><p>Sometimes you need to use the native functionality of the platform and refer to it from the common part.</p><p>In most cases the expect/actual mechanism is enough. In that case, you can use native iOS libraries inside the actual implementation. For example, key-value storage is implemented with SharedPreferences on Android, and with UserDefaults on iOS. In such case, you will have the expect class KeyValueStorage in common:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWS4hFXGo0U1pYGNGx1Nnw.jpeg" /></figure><p>In addition to the expect/actual mechanism, you can use interfaces, where the implementation is put in the DI within the platform.</p><h4>Example with interfaces</h4><pre>//common<br>interface CookieStorage {<br>    suspend fun getCookiesForUrl(link: String): List&lt;Cookie&gt;<br>    suspend fun clearCookie()<br>}<br><br><br>//iOS common implementation<br>class CookieStorageImpl : CookieStorage {<br><br>    override suspend fun getCookiesForUrl(link: String): List&lt;Cookie&gt; { <br>      NSHTTPCookieStorage.sharedHTTPCookieStorage()<br>      …<br>    }<br>       <br>    override suspend fun clearCookie() {<br>        val cookieStore = NSHTTPCookieStorage.sharedHTTPCookieStorage()<br>        ….<br>    }<br>}<br><br>//iOS common di<br>val authPlatformModule = module {<br>    single&lt;CookieStorage&gt; {<br>        CookieStorageImpl()<br>    }    <br>}</pre><p>By the way, this example can be implemented via the <a href="https://android-developers.googleblog.com/2022/10/announcing-experimental-preview-of-jetpack-multiplatform-libraries.html">DataStore KMM implementation</a> by Google.</p><p>One more example of how to implement the interaction with the platform in the common part is to pass a closure to the KMM part from the native part. Although it looks like a hack (you have to use global variables and methods) and sometimes can be avoided.</p><h4>Example with closure</h4><pre>//iOS common<br><br>internal actual fun provideErrorReporters(): List&lt;ErrorReporter&gt; {<br>    return iOSReportersClosure()<br>}<br><br>internal var iOSReportersClosure: (() -&gt; List&lt;ErrorReporter&gt;) = { <br>  emptyList() <br>}<br><br>class iOSDi {<br>    fun setIosReporters(closure: (() -&gt; List&lt;ErrorReporter&gt;)) {<br>        iOSReportersClosure = closure<br>    }<br>}</pre><pre>// iOS native<br>iOSDi().setIosReporters(closure: {<br>    return [IosErrorReporter()]<br>})</pre><p>We almost always use the approach with an interface and platform implementations.</p><h4>Common libraries in native</h4><p>By default, in the native you can use anything that you write in the common module with public visibility.</p><p>But you will have incomplete access to the code of the libraries which you connected in the common.</p><p>To be able to use the libraries from the common in the native iOS part, you need to add an export:</p><pre>cocoapods {<br>    framework {<br>        export(Deps.Kts.Auth.coreAuth)<br>        export(Deps.KmmColors.core)<br>    }<br>}</pre><p>Before starting to develop on KMM, the Android team in Lonto built up some libraries. We were able to split them into the native and the Kotlin parts, and then reuse the Kotlin part in KMM.</p><h3>Implementing specific areas of the project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MOrud5mz49mHhp3NJEQig.jpeg" /></figure><p>In this part of the article we will check out the main aspects of any project, how you can approach them with KMM, and what libraries do we have out there.</p><p>There is a publicly available list of KMM-compatible libraries from the JetBrains developer: <a href="https://github.com/terrakok/kmm-awesome">https://github.com/terrakok/kmm-awesome</a>. Inside you’ll find a large number of libraries. There is a division by sections, so it is easy to navigate there.</p><h4>DI</h4><p>We use Koin as the DI in the KMM part. It’s the most popular library that supports Kotlin, and we’ve had experience with it on Android, which makes it fairly easy to integrate.</p><p>But we can’t use it as a DI in the native iOS part, so we use Swinject. Inside Swinject, the bundle of VC, MVI Store, and other entities is used. And they are only in the iOS part and are not transferred to the common in any way. The MVI Store itself is created in the Koin modules.</p><p>So we have two different dependency graphs: Swinject and Koin. To get them together, we use a layer. It looks like this.</p><p>In the common iOS part, we add a class for the feature called Feature:</p><pre>//shared/src/iOSMain/kotlin/org/example/di/FeatureDi.kt<br>class FeatureDi : KoinComponent {<br><br><br>    fun featureStore(param: Parameter): FeatureStore = get {<br>       parametersOf(param)<br>    }<br>}</pre><p>In the native iOS part:</p><pre>final class FeatureAssembly: Assembly {<br>    <br>    func assemble(container: Container) {<br>        container.register(FeatureViewController.self) { (resolver) in<br>            let store = FeatureDi.featureStore()<br>            return FeatureViewController(store:  store)<br>        }<br>    }<br>}</pre><p>Thus, the methods from FeatureDi KMM are only called inside the Assembly.</p><p>If you need a dependency in the KMM part that is bound to a scope (analogous to Swinject’s custom scope), the scope is created in Koin.</p><p>If necessary, you can tell from the native part at what point to close the scope:</p><pre>class FeatureDi : KoinComponent {<br>   fun closeFeatureFlow() = getScope&lt;FeatureScope&gt;().close()<br>}</pre><p>This layer allows you to make the two DIs of the framework independent of each other.</p><p>Of course, in a perfect world there should be one framework for DI without any layers. It will support both native and cross-platform dependencies. This is how it works on Android with Koin. But I haven’t seen such implementations for iOS yet. If you know any, please leave a comment. 👇</p><h4>Navigation</h4><p>For this part, there are currently no ready-made solutions for KMM that will support navigation both in iOS and Android.</p><p>What’s available:</p><ul><li><a href="https://github.com/AlexGladkov/Odyssey">Odyssey</a> and <a href="https://github.com/adrielcafe/voyager">Voyager</a> support compose multiplatform navigation, but they do not work with iOS.</li><li><a href="https://github.com/arkivanov/Decompose">Decompose</a> allows you to break down functionality into components with regard to lifecycle and add navigation</li></ul><p>These solutions didn’t work for us, because in our projects we need to support navigation considering different implementations of the platform UI (Fragments/UIKit/Compose/SwiftUI) and, accordingly, we need to support different navigation approaches. At the same time, currently we don’t want to radically change the paradigm for creating functionality, as we would have to do with Decompose.</p><p>That’s why we use native navigation now. In iOS this is done through the Coordinator.</p><p><strong>Who is responsible for the navigation logic?</strong></p><p>In most cases, the navigation is simple: just moving between the screens according to the preset rules. In such cases, we notify from the business logic (Store) that some event has occurred. E.g., a request has been created. In the platform part, if the event comes, we navigate to a given screen. If the request has been created, we return to the screen with the list of all requests.</p><p>But sometimes the logic is more complicated. For example, the flow of screens where the transitions are controlled by the business logic. And you can go from each screen to any other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uccGI_rLJNfuQRgt-LrHhg.jpeg" /></figure><p>In this case, the rule above will not work: you will have to create a lot of different events and react to everything on each screen within the flow.</p><h4>Possible navigation events</h4><p>Screen1</p><ul><li>navigateToScreen2</li><li>navigateToScreen4</li></ul><p>Screen2</p><ul><li>navigateToScreen3</li><li>navigateToScreen4</li></ul><p>Screen3</p><ul><li>navigateToScreen2</li><li>navigateToScreen4</li></ul><p>Screen4</p><ul><li>navigateToScreen1</li><li>navigateToScreen3</li><li>navigateToScreen5</li></ul><p>In such cases, we create an event NavigateTo(screen). When the platform part accepts this event, it goes to the screen with no additional calculation. And the state machine with transition logic is in the general part.</p><h3>Network</h3><p>When working with the network with libraries, everything is ok.</p><p>We have <a href="https://ktor.io/">Ktor</a> that allows us to send cross-platform queries. You can configure all the necessary functionality in it. Under the hood, a native engine is used to execute queries, such as URLSession.</p><p>If you have GraphQL, there is an <a href="https://www.apollographql.com/docs/kotlin/">Apollo</a> client for pure Kotlin. It works just fine in KMM.</p><p>When working with the network, we had a problem with sending files through Ktor: how to send a file to the server using streams, that is without uploading it completely into the memory.</p><p>In Ktor, you can send form fields using a special class: <a href="https://api.ktor.io/ktor-io/io.ktor.utils.io.core/-input/index.html">Input</a>. It is abstracted from the content. In Android, you can get an InputStream from a file and convert it to Input using an <a href="https://github.com/ktorio/ktor/blob/0081f943b434bdd0afd82424b389629e89a89461/ktor-io/jvm/src/io/ktor/utils/io/streams/Input.kt">extension</a>. This way, when sending a file, bytes from the file InputStream will be read, and the file will not be saved in the memory.</p><p>In iOS, there is no out of the box solution to get Input for a file (the file is obtained from the URL). You have to write the transfer logic yourself.</p><p>You can also use ByteArray to send the file, but then the whole file is put into memory.</p><h4>Example of implementation for ByteArray</h4><pre>let data = Data(contentsOf: url)<br>let byteArray = data.toArray(type: UInt8.self)<br>let kotlinByteArray = KotlinByteArray.init(size: Int32(byteArray.count))<br>let intArray: [Int8] = byteArray.map {<br>    Int8(bitPattern: $0)<br>}<br>for (index, element) in intArray.enumerated() {<br>    kotlinByteArray.set(index: Int32(index), value: element)<br>}</pre><p>We used this option because it suited our task: we could only choose small files.</p><h4>UI</h4><p>KMM has nothing to offer on the UI side yet, but it didn’t aim in this direction anyway. There is a <a href="https://blog.jetbrains.com/ru/kotlin/2021/12/compose-multiplatform-1-0-is-going-live/">compose multiplatform</a> that works steadily on Android and desktop, but in iOS it is only in preview. You can see work examples <a href="https://www.youtube.com/watch?v=Lw2JopLvOuc">here</a>.</p><p>The iOS compose multiplatform is still far away from being stable, so we use native UI: SwiftUI, UIKit.</p><p>But still, in KMM, you can share something in the presentation layer (we use <a href="https://github.com/icerockdev/moko-resources">MOKO-Resources</a> for this):</p><ul><li>strings with translations</li><li>colors</li><li>images, only bitmap by default; you can use <a href="https://github.com/icerockdev/moko-resources/issues/29">workarounds</a>, the <a href="https://github.com/jcraane/kmm-images">kmm-images library</a></li><li>fonts</li></ul><p>Under the hood, the library generates native resources for each platform from KMM at the project compiling stage.</p><p>In addition, we’ve reused the themes of the app between the platforms so that when you change night mode the theme automatically changes. We plan to write an article about this implementation.</p><h3>Debugging an app</h3><p>When debugging an app, the problem of multiple IDEs comes up. You can either debug with Xcode using the <a href="https://github.com/touchlab/xcode-kotlin">xcode-kotlin</a> plugin or with AndroidStudio, AppCode. Our developers use both approaches, depending on personal preference.</p><h3>Crashes</h3><p>When a crash occurs in the KMM part, the error always points to the assembly code. But to figure out the causes of the error it is useful to check out the stack trace of the flow. It helps to find out approximately where the error occurred. You can also go to the KMM file by clicking on a stack trace frame. But the exact location of the error won’t be highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vK3HRxebGJxxnrboILgLBA.jpeg" /></figure><p>There may also be problems with the display of logs in Crashlytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4h-P27iQE63Dcp19xK1_EA.jpeg" /></figure><p>You can use <a href="https://github.com/touchlab/CrashKiOS">CrashKit</a> for more detailed information.</p><h3>Logging non-critical errors</h3><p>Non-critical error logging in KMM is almost invariable regarding native development.</p><ol><li>We create an ErrorReporter interface that can log errors to the service:</li></ol><pre>interface ErrorReporter {<br>    fun setUserId(userId: String)<br>    fun logError(throwable: Throwable)<br>}</pre><p>2. We create a composite reporter to be able to send errors to different services:</p><pre>class CompositeErrorReporter(<br>    private val reporterList: List&lt;ErrorReporter&gt;<br>) : ErrorReporter {<br><br>    override fun setUserId(userId: String) {<br>        reporterList.forEach { it.setUserId(userId) }<br>    }<br><br>    override fun logError(throwable: Throwable) {<br>        reporterList.forEach { it.logError(throwable) }<br>    }<br>}</pre><p>3. We provide platform loggers:</p><pre>//Common<br>internal expect fun provideErrorReporters(): List&lt;ErrorReporter&gt;<br><br>  //DI<br>factory&lt;ErrorReporter&gt; {<br>    CompositeErrorReporter(<br>        reporterList = provideErrorReporters()<br>    )<br>}<br><br>//Common iOS<br>internal actual fun provideErrorReporters(): List&lt;ErrorReporter&gt; {<br>    return iosReportersClosure()<br>}<br><br>internal var iosReportersClosure: (() -&gt; List&lt;ErrorReporter&gt;) = { emptyList() }</pre><pre>//Native iOS<br>@objc class CrashlyticsIosErrorReporter: NSObject, ErrorReporter {<br>    func logError(throwable: KotlinThrowable) {<br>      // send throwable to crashlytics<br>    }<br>}<br><br>iOSDi().setIosReporters(closure: {<br>    return [IosErrorReporter()]<br>})</pre><p>The native reporter could potentially be moved to common ios.</p><p>4. In common we create a connection between the logger and the reporter. We use <a href="https://github.com/AAkira/Napier">Napier</a> as our logger.</p><pre>class ErrorReporterAntilog(<br>    // CompositeErrorReporter is substituted as ErrorReporter<br>    private val errorReporter: ErrorReporter <br>) : Antilog() {<br>    override fun performLog(...) {<br>         errorReporter.logError(exception)<br>    }<br>}</pre><pre>//when running app in iOS native<br>Napier.releaseBuild(antilog: ErrorReporterAntilog…)</pre><h3>Memory leaks</h3><p>One of the things you have to deal with when developing an app is making sure that there are no memory leaks. In iOS it is a hard task even without KMM: there are no tools to timely detect memory leaks.</p><p>You should use the <a href="https://developer.apple.com/documentation/xcode/gathering-information-about-memory-use">Memory Graph Debugger</a> to periodically check that nothing has leaked. Or <a href="https://medium.com/bitso-engineering/finding-memory-leaks-in-ios-like-a-pro-83a0212309b6">write tests</a> and run them on CI. Android has a <a href="https://github.com/square/leakcanary">leakcanary</a> library that allows you to check for basic leaks related to the framework. Unfortunately, there is no similar solution for iOS.</p><p>With KMM, we can resort to the same leak-tracking techniques in iOS as in native:</p><ol><li>At some point we realize that something is going wrong 🙈:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*wcXxnVm2yJVi_-a6Swi_Ww.jpeg" /></figure><p>2. We open the Memory Graph Debugger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unkZnuSM4xgN_izKPHN0Lg.jpeg" /></figure><p>3. We see additional info about the leaking object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbtCjlpUT-7IWZVY_bQUoQ.png" /></figure><p>As you can see from the figure above, nothing in it indicates where the leak happened. And in our experience, there are always library guts in the leaks. So it can take a long time to find the problem.</p><h3>Process</h3><p>To describe the process, let’s consider a project with four mobile developers: two for Android and two for iOS. The iOS developers had no experience with KMM before.</p><p>At first, the Android team develops the KMM features in the project, and the iOS team plugs them when they are ready, tweaking only the UI part.</p><p>Over time, iOS developers join the code review of the KMM part in observation mode. A few months later, iOS developers are already implementing template features and logic edits within KMM. After another couple of months, iOS developers are fully proficient in KMM development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HLDJJ0YVEeovpSw9CyJZA.jpeg" /></figure><p>In November, part of the Android team was on vacation, so iOS developers did most of the KMM tasks.</p><p>When considering the timeline, please note that our team did not have a goal to teach iOS developers to implement KMM as quickly as possible. Given an existing project with approved and established approaches, this can be done even faster.</p><p>We also went through the process of changing the division of feature implementation process into independent parts:</p><ol><li>Initially, there were three objectives for the feature: KMM, Android, and iOS. Firstly, the KMM task was performed, and then the two platform tasks. This approach worked badly for us: at the time of implementing a native task (e.g. for Android) it turned out that we had missed something in KMM and needed to refine the KMM module. But the rework also affected the other platform, which by that time could have been in the process, and we had to rework it.<br>We did not collect statistics on the number of such tasks, but we felt there were about 60–70%. And every developer was spotting this problem on retro.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQXyX8A5UxehsYgj048O4w.jpeg" /></figure><p>2. Now we divide the implementation of the task into two parts: KMM + the first platform, and the second platform. That is, at first we develop the KMM with a platform part, such as Android, if the Android team was the first to come to the implementation of the functionality. After that, the second platform part is developed, e.g. iOS. This is how we reduced the rework in KMM. Although they do happen when the API of one of the platforms is not okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYEJi5KbN6c6SUCHs887MQ.jpeg" /></figure><p>Another thing I would like to point out is that since we use a monorepo, any developer can affect the KMM part in their task. And changes there can break platforms.</p><p>Example. An Android developer changed the KMM, which broke the iOS part. And the developer might not even have seen it, because he never builds an iOS project locally. You can control it by tests, but it is minimally enough to add the “autobuild IOS and Android projects” step in CI before closing the merge request.</p><p>So that the guys who implement KMM understand how it integrates with platforms they don’t understand, we held sessions explaining the basic components and how they relate to Android and iOS. These sessions also helped developers of neighboring platforms to better localize bugs and even to fix not-so-sophisticated bugs when there are changes in KMM.</p><p>In theory, not all Android developers can have a working MacOS machine. In this case, you will need the help of iOS developers to integrate KMM with iOS and edits.</p><h3>Bottom line</h3><h4>Technology Status</h4><ul><li>KMM has its nuances, and we discussed them in the article. But during the development period we did not encounter any blockers that made us think about abandoning KMM and going back to the native or moving to another cross-platform technology.The iOS developers <strong>embraced KMM well</strong>: everyone on our team has a desire to write a cross-platform part. That said, I’m sure it won’t be the case for all developers in general.</li></ul><h4>Personal impression</h4><ul><li>The iOS developers <strong>embraced KMM well</strong>: everyone on our team has a desire to write a cross-platform part. That said, I’m sure it won’t be the case for all developers in general.</li><li>The iOS and Android teams have become <strong>more united</strong>: not only they discuss common development concepts now, but also common implementation.</li></ul><h4>Business</h4><p>In general, the article is not intended to justify KMM to business, but without these conclusions it looks incomplete.</p><ul><li>Savings in development time depends on the project.<br>In our current projects, the ideal time saving is about <strong>25%</strong>. The ratio of time spent on business logic implementation to time spent on UI is 50/50. So, we reduce the implementation of the business logic on one of the platforms. In reality the saving is less: developers need to immerse themselves in the new technology, occasionally there are reworks in the KMM part depending on the platforms, and infrastructure difficulties.<br>It is difficult to estimate <em>exactly</em> how much less: to do this, you need to compare the native vs KMM on the same projects. The time saving will be greater if the projects have a lot of business logic on the mobile client: offline-first solutions.</li><li><strong>Almost 50%</strong> time saving on rework if only the backend/logic is changed without changing the UI.</li><li>The time for iOS developers to immerse themselves in KMM from 0 to implementing complex features is <strong>about 4 months</strong>. And it was not our team’s goal to teach iOS developers how to implement KMM as quickly as possible. Given an existing project with approved and established approaches, this can be done even faster.</li><li><strong>The bus factor increases</strong>: if the iOS team lacks time, is busy on another project, or is on vacation, Android devs can refine KMM logic instead of them.</li><li>We were able to transition to cross-platform <strong>without additional hiring</strong> or <strong>retraining</strong> people.</li><li>Our approach to developing the KMM part is not too different from the native Android approach, which we have been working on for a long time. And it speeds up the immersion of a new teammate into KMM quite a bit: a new Android developer recently joined us, and <strong>in less than a week</strong> he was able to work on the KMM part. Part of that time was spent on diving into the MVI approach.</li></ul><p>We welcome you to share your comments about using KMM in the mobile development team. How do you involve iOS developers in cross-platform development?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c23cded1a50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through iOS Developer’s Eyes</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Corporate mobile app: all pros and cons]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/corporate-mobile-app-all-pros-and-cons-82b9dca3c4bc?source=rss-23be660aa73e------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b9dca3c4bc</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Maxim  Myalkin]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 13:56:39 GMT</pubDate>
            <atom:updated>2023-05-22T07:43:30.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMjU0js9S4rwpgfSuU3tPw.jpeg" /></figure><p>Mobile apps change the market in all industries: from food deliveries to construction companies. If you are thinking about creating an app for your business, we advise you to take into account a few things. Maxim Myalkin, head of mobile development at <a href="https://www.lonto.io/">Lonto</a>, shares his expertise in creating your own app, when it is profitable and not.</p><p>Users spend 88% of their phone time in apps. They are convenient because through apps one can solve many problems ― make purchases, acquire knowledge, make an appointment with a doctor. Applications can be customized to the needs of any business: 33% of companies in America have already created their own mobile service.</p><h3>Let’s start with pros</h3><p><strong>Purchase conversion in apps is higher.</strong> The first reason why companies create their own services is that apps generate more sales than sales web sites: they make 63% of purchases and conversion there is four times higher. Besides, mobile apps can help optimize workflows, get closer to the target audience, develop strong customer loyalty and reduce the company’s costs.</p><p><strong>Automation of a company’s business processes.</strong> Optimization of a company’s internal processes leads to the effective work of specialists and an increase in business profitability. Employees must promptly receive information about changes in the workflow in order to have time to react and not let the client down. Popup notifications in apps are more difficult to miss than messages in the department chat or in the mail. Firstly, there are fewer of them and secondly they are always visible.</p><p>It is easier for managers to control the workflow when all tasks and problems are seen in one place. For example, Uber made an app specifically for their drivers. Before creating the app, clients had to contact the manager and then the manager sent data to drivers. Now there is no need for an extra contact chain, all work is done by AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yx8I-pQjPz0DU5yf" /><figcaption><strong>The interface of Uber — Driver</strong></figcaption></figure><p><strong>Increasing customer loyalty.</strong> It is important to motivate consumers to repurchase, because finding a new customer will cost 5–10 times more than retaining an existing one. The app will help you optimize the work with the target audience and stand out among competitors.</p><p>A good example is the loyalty system in coffee shops, when they offer the seventh cup of coffee as a gift. It is much easier with an app to track all purchased cups — data can’t be lost or forgotten as a list of paper. One of the first coffee shops in the world to create its own app was Starbucks. The service has 25 million users around the world, who create 53% of the annual company’s income.</p><p><strong>Cost reduction. </strong>Starbucks’s application optimizes the work of the company itself: 4 out of 5 visitors prefer to pay for the order in the application and pick it up on their own. The coffee shop receives more resources for development, reducing employee costs.</p><p>Another example is the cosmetic brand Sephora. The company allows customers to virtually appreciate different shades of cosmetics. This is how the business saves on rent and test samples, reducing the costs of offline stores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NJ7JtjE4xSwOSqdG" /><figcaption><strong>Sephora brand app</strong></figcaption></figure><p>Closer to the target audience. The mobile app is one of the channels for connection with clients. Additional contact points make the company more “real” for users. Services make it easier for customers to communicate with you: they do not need to go anywhere or call, they can ask questions at any convenient time. Thus, you optimize the work of the support service and “tie” customers to the company’s service. And through pop-up notifications, you will be able to inform the audience about promotions, discounts and upcoming events.</p><h3>As for the cons</h3><p>However, corporate mobile apps also have cons that can be stronger than pros.</p><p><strong>High costs for creation and support.</strong> The development of your own app will require $40,000 to $150,000 and can exceed $300,000 in some cases. Let alone implementation which can take up to two months. Likely, you will need to periodically update the service which will also have additional costs. For small and medium-sized businesses, development and maintenance costs may be too high. Use a standard solution to start to understand whether you need to develop your own application — it is cheaper and easier. For example, AppMachine and BuildFire application builders.</p><p><strong>​​The benefit depends on the number of users</strong>. The more people use the mobile service, the more effective it is. If your company focuses on a small target, or you have a seasonal business, it is more profitable to create a mobile version of a corporate website: easier, faster and does not require installation.</p><h3>Summary</h3><p>Mobile services optimize the company’s work and the process of interaction with customers: despite the arguments against it, they remain the main trend in business development. However, development of a corporate app is not for everyone.</p><p>If your business is focused on a narrow consumer target, is seasonal or does not have the resources to create and support a mobile service, take a closer look at standard solutions or adapt the web version for mobile devices.</p><p>If your business is focused on the mass consumer, you have resources to develop and support the app, but you do not know if you need it, take a standard solution for the “test period” to understand what problems and tasks your own service will help you solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b9dca3c4bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/corporate-mobile-app-all-pros-and-cons-82b9dca3c4bc">Corporate mobile app: all pros and cons</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Android OAuth with AppAuth library]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/implementing-android-oauth-with-appauth-library-b99dc2301b3?source=rss-23be660aa73e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b99dc2301b3</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Maxim  Myalkin]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 08:49:32 GMT</pubDate>
            <atom:updated>2023-05-22T07:45:08.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnLHMhbgroDFkhcSiBHo4A.jpeg" /></figure><p>Hey! My name is Maxim Myalkin, I am a mobile lead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>In this series of article, I am going to explain OAuth nuances in mobile applications in a structured way: which points should be noticed, which methods of implementation to choose. I am also going to share my experience in configuring OAuth in an Android app using the AppAuth library.</p><p>In a previous article we reviewed OAuth mobile implementation details, how Authorization Code Flow with PKCE works, implementation options.</p><ol><li><a href="https://medium.com/kts-digital-services-integrator/oauth-mobile-implementation-details-8d65aced9a7f">OAuth mobile implementation details</a></li><li>Implementing Android OAuth with AppAuth library (you are here)</li><li><a href="https://medium.com/kts-digital-services-integrator/how-to-add-oauth-in-ios-in-half-an-hour-601ff8fdca4">Implementing iOS OAuth in 30 minutes</a></li></ol><p>Сontent of <em>this</em> article:</p><p><strong>Implementation in the Android application<br> \ </strong>General setup<br> \ Implementation in Android<br> \ Authorization<br> \ Logout<br> \ Token refreshing<br><strong>Conclusion</strong></p><h3>Implementation in the Android application 📱</h3><p>Let’s see how we can implement OAuth in your Android app using the AppAuth library.<a href="https://github.com/MaxMyalkin/android-oauth-example"> The code is available on GitHub</a>.</p><p>The application is simple: displaying information about my GitHub profile.</p><p>To do this, each time you launch the app, we will open the GitHub authorization page. After successful authorization, we navigate the user to the main page, on the main page user can get information about the current profile.</p><p>We need to pay attention to 3 key points:</p><ul><li>user authorization</li><li>updating the token</li><li>user logout</li></ul><h3>General setup 🛠</h3><p><a href="https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app">The first step is to register the OAuth application in GitHub.</a></p><p>Set the CALLBACK_URL for your app on the service on the registration page. User will be redirected to this URL after successful authorization, and your app will intercept it.</p><p>We will use <em>com.kts.oauth://github.com/callback</em> as the CALLBACK_URL</p><p>You should use the custom scheme <em>com.kts.oauth</em> so that only your app can intercept the redirect.</p><p>After registration, you should have <em>client_id</em> and <em>client_secret</em> (it should be generated on OAuth app registration). Save them.</p><p>Next, you need to find the authorization URL on the GitHub service, and URL to exchange the authorization code for a token. The answer can be found in the<a href="https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps"> GitHub OAuth documentation</a>.</p><p><strong>URL for authorization:</strong><a href="https://github.com/login/oauth/authorize"><strong> https://github.com/login/oauth/authorize</strong></a><strong><br>URL for token exchange:</strong><a href="https://github.com/login/oauth/access_token"><strong> https://github.com/login/oauth/access_token</strong></a></p><p>For OAuth process, we need to identify the scopes that github will grant access to after user authorization. Our app needs access to the user’s information and repositories in the app, so the scopes are: <strong>user, repo</strong>.</p><p>The general parameters have been defined. Let’s move on to Android implementation.</p><pre>implementation &#39;net.openid:appauth:0.9.1&#39;</pre><p>Let’s write all OAuth settings to Kotlin object <strong>AuthConfig</strong> to make it easy to work with:</p><pre>object AuthConfig {<br>   const val AUTH_URI = &quot;https://github.com/login/oauth/authorize&quot;<br>   const val TOKEN_URI = &quot;https://github.com/login/oauth/access_token&quot;<br>   const val END_SESSION_URI = &quot;https://github.com/logout&quot;<br>   const val RESPONSE_TYPE = ResponseTypeValues.CODE<br>   const val SCOPE = &quot;user,repo&quot;<br>   const val CLIENT_ID = &quot;...&quot;<br>   const val CLIENT_SECRET = &quot;...&quot;<br>   const val CALLBACK_URL = &quot;ru.kts.oauth://github.com/callback&quot;<br>   const val LOGOUT_CALLBACK_URL = &quot;ru.kts.oauth://github.com/logout_callback&quot;<br>}</pre><p>Compared to the general setting, the following parameters has been added:</p><ul><li><strong>RESPONSE_TYPE</strong>. Use the “code” constant from the AppAuth library. This constant is responsible for returned value to the client after successful authorization in the browser. Options: code, token, id_token.</li></ul><p>According to the OAuth Authorization Code Flow, we need a <strong>code</strong>.</p><p>In fact, GitHub API does not require the response_type parameter to be passed and always returns only the code. However, this parameter may be required for other services.</p><p><strong>END_SESSION_URI, LOGOUT_CALLBACK_URL</strong>. Settings required for the logout.</p><h3>Authorization 🗣</h3><p>Now let’s open the authorization page using Chrome Custom Tabs.</p><p>The AppAuth library provides the <strong>AuthorizationService</strong> class to work with CCT and perform automatic operations of code exchange for a token. <strong>AuthorizationService </strong>instance should be created when you enter the screen. When you exit the screen, it should be cleared. In the example, this is done inside the <strong>ViewModel</strong> authorization screen.</p><p>Creating in ViewModel init block:</p><pre>private val authService: AuthorizationService = AuthorizationService(getApplication())</pre><p>Clear in ViewModel.onCleared:</p><pre>authService.dispose()</pre><p>To open the authorization page in CCT, you need an android intent. To get intent, we are creating the <strong>AuthorizationRequest</strong> based on the <strong>AuthConfig</strong> data:</p><pre>private val serviceConfiguration = AuthorizationServiceConfiguration(<br>   Uri.parse(AuthConfig.AUTH_URI),<br>   Uri.parse(AuthConfig.TOKEN_URI),<br>   null, // registration endpoint<br>   Uri.parse(AuthConfig.END_SESSION_URI)<br>)<br><br>fun getAuthRequest(): AuthorizationRequest {<br>   val redirectUri = AuthConfig.CALLBACK_URL.toUri()<br>   return AuthorizationRequest.Builder(<br>       serviceConfiguration,<br>       AuthConfig.CLIENT_ID,<br>       AuthConfig.RESPONSE_TYPE,<br>       redirectUri<br>   )<br>       .setScope(AuthConfig.SCOPE)<br>       .build()<br>}</pre><p>Create an intent:</p><pre>// here you can configure the chromeCustomTabs ui<br>val customTabsIntent = CustomTabsIntent.Builder().build()<br><br>val openAuthPageIntent = authService.getAuthorizationRequestIntent(<br>   getAuthRequest(),<br>   customTabsIntent<br>)</pre><p>After that, open the Activity by intent. We need to process the activity result to get the code.</p><p>Therefore, use <strong>ActivityResultContracts</strong>. You can also use <strong>startActivityForResult</strong>.</p><pre>private val getAuthResponse = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {<br>   val dataIntent = it.data ?: return<br>   handleAuthResponseIntent(dataIntent)<br>}<br><br>getAuthResponse.launch(openAuthPageIntent)</pre><p>Under the hood Activity from the AppAuth library will be opened (<strong>AuthorizationManagementActivity</strong>), which will take responsibility for opening the CCT and processing the redirect. And the result of the operation will be passed to the activity of your application (<strong>AppActivity</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8NYcouneK-j2F3tvtwEDQ.png" /><figcaption><em>Activity stack diagram</em></figcaption></figure><p>All the information that we previously specified in AuthConfig, as well as the generated code_challenge, will be passed to <strong>openAuthPageIntent</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiBQLKSLI3u93ssEfaHqyw.jpeg" /></figure><p>AppAuth automatically generates an URL to open the login page:</p><pre>https://github.com/login/oauth/authorize?redirect_uri=ru.kts.oauth%3A%2F%2Fgithub.com%2Fcallback&amp;client_id=3fe9464f41fc4bd2788b&amp;response_type=code&amp;state=mrhOJm7ot4C1aE9ND3lWdA&amp;nonce=4zVLkQrhQ4L46hfQ1jdTHw&amp;scope=user%2Crepo&amp;code_challenge=gs23wPEpmJYv3cdmTRWNSQLvvnPtHUhtSv4zhbfKS_o&amp;code_challenge_method=S256</pre><p>We should specify that our application can handle URLs with our custom scheme <strong>com.kts.oauth </strong>to process auth redirect.</p><p>To do this, specify manifest placeholder inside the <strong>defaultConfig </strong>of<strong> </strong>app <strong>build.gradle</strong>:</p><pre>manifestPlaceholders = [<br>   appAuthRedirectScheme: &quot;ru.kts.oauth&quot;<br>]</pre><p>After that, activity <strong>RedirectUriReceiverActivity</strong> that handles URLs with custom scheme will be added to your app’s AndroidManifest.xml automatically. Merged manifest:</p><pre>&lt;activity <br>    android:name=&quot;net.openid.appauth.RedirectUriReceiverActivity&quot;<br>    android:exported=&quot;true&quot; &gt;<br>    &lt;intent-filter&gt;<br>      ...<br>      &lt;data android:scheme=&quot;ru.kts.oauth&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/activity&gt;</pre><p>You can also set up a redirect using standard schemes. You can read more in the<a href="https://github.com/openid/AppAuth-Android"> AppAuth docs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*tmJVJJmPaJnY8SnDjAeUVw.png" /></figure><p>Next, you need to get an authorization code and exchange it for a token. In this case, an authorization error may occur, and it should be handled.</p><p>The AppAuth lets you get an error or request from the result intent to exchange the code for a token:</p><pre>private fun handleAuthResponseIntent(intent: Intent) {<br>   // пытаемся получить ошибку из ответа. null - если все ок<br>   val exception = AuthorizationException.fromIntent(intent)<br>   // пытаемся получить запрос для обмена кода на токен, null - если произошла ошибка<br>   val tokenExchangeRequest = AuthorizationResponse.fromIntent(intent)<br>       ?.createTokenExchangeRequest()<br>   when {<br>       // авторизация завершались ошибкой<br>       exception != null -&gt; viewModel.onAuthCodeFailed(exception)<br>       // авторизация прошла успешно, меняем код на токен<br>       tokenExchangeRequest != null -&gt;<br>           viewModel.onAuthCodeReceived(tokenExchangeRequest)<br>   }<br>}</pre><p>The token request will be created automatically and the code_verifier will be added to it. Therefore, the saving code_verifier and code_verifier has already been done by AppAuth.</p><p>We are not going to consider the option with an authorization error. You can show Toast or Snackbar in this case.</p><p>We received a tokenExchangeRequest request that needs to be performed. To do this, use <strong>AuthService.performTokenRequest </strong>method.</p><p>Under the hood, the performTokenRequest method runs the legacy AsyncTask, so the library API uses callbacks.</p><pre>fun performTokenRequest(<br>   authService: AuthorizationService,<br>   tokenRequest: TokenRequest,<br>   onComplete: () -&gt; Unit,<br>   onError: () -&gt; Unit<br>) {<br>   authService.performTokenRequest(tokenRequest, getClientAuthentication()) { response, ex -&gt;<br>       when {<br>           response != null -&gt; {<br>               //обмен кода на токен произошел успешно, сохраняем токены и завершаем авторизацию<br>               TokenStorage.accessToken = response.accessToken.orEmpty()<br>               TokenStorage.refreshToken = response.refreshToken<br>               onComplete()<br>           }<br>           //обмен кода на токен произошел неуспешно, показываем ошибку авторизации<br>           else -&gt; onError()<br>       }<br>   }<br>}</pre><p>The callback interface can be easily turned into a suspend call and used together with coroutines in your application. You can see an<a href="https://github.com/MaxMyalkin/android-oauth-example/blob/master/app/src/main/java/com/kts/github/data/auth/AppAuth.kt#L56"> example in the project</a>.</p><p>When exchanging a code for a token, we need to<a href="https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github"> send client_secret according to the Github documentation.</a> Therefore, when calling the <strong>performTokenRequest</strong> method, you need to pass the <strong>ClientAuthentication</strong> instance. The library has several implementations: <strong>ClientSecretBasic</strong>, <strong>ClientSecretPost</strong>, <strong>NoClientAuthentication</strong>. You need to choose based on server requirements.</p><p>For GitHub you should send client_secret by ClientSecretPost:</p><pre>private fun getClientAuthentication(): ClientAuthentication {<br>   return ClientSecretPost(AuthConfig.CLIENT_SECRET)<br>}</pre><p>If the service does not require client_secret, you can use <strong>ClientSecretBasic(“”)</strong>.</p><p>And we finished the authorization implementation in GitHub using the AppAuth library.</p><p>Lets’s describe the steps briefly.</p><ol><li>Connect the AppAuth library.</li><li>Create AuthConfig.</li><li>Specify manifestPlaceholder appAuthRedirectScheme.</li><li>Create AuthorizationService instance, for example, in ViewModel.</li><li>Authorize user:<br>→ create an AuthorizationRequest<br>→ create intent;<br>→ launch activity with CCT.</li><li>Exchange the code for a token:<br>→ get TokenExchangeRequest from activity result intent;<br>→ perform TokenExchangeRequest using authService.performTokenRequest;<br>→ save tokens in the success callback.</li></ol><h3>Logout 📤</h3><p>For a logout, we need not only to clear the token inside the app, but also to clear browser cookies. You can’t do that from your application, because the browser is an external application. To do this, you need to open the web page that will clear browser cookies.</p><p>For GitHub webpage is<a href="https://github.com/logout"> https://github.com/logout</a><strong>.</strong> We previously specified this constant in AuthConfig.END_SESSION_URI.</p><p>The idea for opening the page is the same as for the login page:</p><ol><li><strong>Create a logout request:</strong></li></ol><pre>val endSessionRequest = EndSessionRequest.Builder(authServiceConfig)<br> //Требуется для некоторых сервисов, idToken получается при авторизации аналогично accessToken и refreshToken<br>  .setIdTokenHint(idToken) <br>  // uri на который произойдет редирект после успешного логаута, не везде поддерживается<br>  .setPostLogoutRedirectUri(AuthConfig.LOGOUT_CALLBACK_URL.toUri()) <br>  .build()</pre><p><strong>2. Create a custom tabs intent:</strong></p><pre>val customTabsIntent = CustomTabsIntent.Builder().build()</pre><p><strong>3. Create a activity intent:</strong></p><pre>val endSessionIntent = authService.getEndSessionRequestIntent(<br>    endSessionRequest,<br>    customTabsIntent<br>)</pre><p><strong>4. Open the logout page:</strong></p><pre>private val logoutResponse = registerForActivityResult(<br> ActivityResultContracts.StartActivityForResult()<br>) {}<br><br>logoutResponse.launch(endSessionIntent)</pre><p>The user goes to the logout page, where the browser session is cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*u3_CGgou8LXi2v8wi3LX8w.jpeg" /></figure><p>After successful logout, application should intercept the redirect to it. Not all services redirect to app after the successful logout (GitHub does not redirect). Therefore, the user will need to click on the close button in CCT.</p><p>After manual closing of CCT activity, app get activity result=<strong>cancelled</strong>, because there was no redirect to the application.</p><p>In our example with GitHub, we clear the session anyway and navigate to the application login page.</p><pre>private val logoutResponse = registerForActivityResult(<br> ActivityResultContracts.StartActivityForResult()<br>) {<br>   // очищаем сессию и переходим на экран логина<br>   viewModel.webLogoutComplete()<br>}</pre><h3>Token refreshing 🥦</h3><p>When working with OAuth and the AppAuth library, it is important to keep access tokens up to date. access_token received from the server may be expired. In order to not navigate the user to login page, you need to refresh the token. This is done using refresh_token.</p><p>The refresh process is similar to tokenExchangeRequest:</p><ol><li><strong>Create token refresh request</strong></li></ol><pre>val refreshRequest = TokenRequest.Builder(<br>   authServiceConfig,<br>   AuthConfig.CLIENT_ID<br>)<br>   .setGrantType(GrantTypeValues.REFRESH_TOKEN)<br>   .setScopes(AuthConfig.SCOPE)<br>   .setRefreshToken(TokenStorage.refreshToken)<br>   .build()</pre><p>It is important to take into account 2 lines:</p><pre>.setGrantType(GrantTypeValues.REFRESH_TOKEN)<br>.setRefreshToken(TokenStorage.refreshToken)</pre><p>As grantType, pass the “refreshToken” string, and pass the <strong>refresh_token</strong> received during authorization.</p><p><strong>2. Execute the token refresh request:</strong></p><pre>authorizationService.performTokenRequest(refreshRequest) { response, ex -&gt;<br>   when {<br>       response != null -&gt; emitter.onSuccess(response)<br>       ex != null -&gt; emitter.tryOnError(ex)<br>       else -&gt; emitter.tryOnError(IllegalStateException(&quot;response and exception is null&quot;))<br>   }<br>}</pre><p>This code can be used in the places where you are updating the token in the project. For example, in OkHttp interceptor. The full interceptor example can be found in the<a href="https://github.com/MaxMyalkin/android-oauth-example/blob/master/app/src/main/java/com/kts/github/data/network/AuthorizationFailedInterceptor.kt%C2%A0"> repository</a>.</p><p>If the token refresh failed (for example, <strong>refresh_token</strong> is invalid), you should logout the user.</p><p>See the logout example 👆👆</p><p><a href="https://docs.github.com/en/developers/apps/getting-started-with-apps/differences-between-github-apps-and-oauth-apps">Access tokens are never expired in the GitHub service</a>, so the refresh example can be used in other services.</p><h3>Conclusion 🧐</h3><p>The full project code is in<a href="https://github.com/MaxMyalkin/android-oauth-example"> my GitHub repository</a>.</p><p>In this article we reviewed OAuth implementation details in mobile applications, and an example of Android app OAuth implementation using the AppAuth library. This implementation will allow you to quickly setup OAuth in your app.</p><p>According to our experience, AppAuth makes it easier to work with OAuth in the mobile application, saving you from writing implementation details manually. However, it creates requirements for an authorization server. If the auth service does not comply with RFC-8252 (OAuth 2.0 for Native Apps), AppAuth may not provide required auth features.</p><p>Share in the comments, how did you implement OAuth in mobile apps? Did you have any problems? Did you use AppAuth?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b99dc2301b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/implementing-android-oauth-with-appauth-library-b99dc2301b3">Implementing Android OAuth with AppAuth library</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth mobile implementation details]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/oauth-mobile-implementation-details-8d65aced9a7f?source=rss-23be660aa73e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d65aced9a7f</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Maxim  Myalkin]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 13:25:33 GMT</pubDate>
            <atom:updated>2023-05-22T07:44:03.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKMVLwnpK_tK1beM0XkrFA.jpeg" /></figure><p>Hey! My name is Maxim Myalkin, I am a mobile lead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>No service can be used without a login. Often mobile apps require login via third-party social networks, for example, Google or Meta. And when training mobile development, open APIs are used, where OAuth is used for authorization.</p><p>Therefore, mobile app developers have to work with OAuth. There are different materials on this topic on the internet.</p><p>In this series of article, I am going to explain OAuth nuances in mobile applications in a structured way: which points should be noticed, which methods of implementation to choose. I am also going to share my experience in configuring OAuth in an Android app using the AppAuth library.</p><ol><li>OAuth mobile implementation details (you are here)</li><li><a href="https://medium.com/kts-digital-services-integrator/implementing-android-oauth-with-appauth-library-b99dc2301b3">Implementing Android OAuth with AppAuth library</a></li><li><a href="https://medium.com/kts-digital-services-integrator/how-to-add-oauth-in-ios-in-half-an-hour-601ff8fdca4">Implementing iOS OAuth in 30 minutes</a></li></ol><p>Сontent of <em>this</em> article:</p><p><strong>OAuth and flow<br>How Authorization Code Flow with PKCE works<br>Intercepting auth by malicious app<br>Implementation details <br>→ </strong>How to open the login page:<br><strong>→→</strong> <em>WebView<br> </em><strong>→→</strong><em> Browser<br> </em><strong>→→</strong><em> ChromeCustomTabs, SafariVC<br></em><strong>→</strong><em> </em>Redirect doesn’t work in Chrome<br><strong>→</strong> Token refreshing<br><strong>→</strong> Missing browser<br><strong>→</strong> Logout<br><strong>OAuth implementation options<br>→ </strong>Service SDK<br><strong>→</strong> Manual implementation<br><strong>→</strong> OAuth libraries</p><h3>📱OAuth and flow</h3><p>When it comes to authorization and authentication, concepts such as OAuth2 and OpenID are used. In this article I am not going to disclose them, on Medium there <a href="https://itnext.io/an-oauth-2-0-introduction-for-beginners-6e386b19f7a9">is already such material</a>.</p><p>Below we are going to look at the details regarding mobile development. For our purposes, the differences between OAuth2 and OpenID are irrelevant, so we are going to use the overall term OAuth.</p><p>There are different flow in OAuth, but not all are suitable for use in the application:</p><ul><li><strong>Authorization Code Flow. </strong>Not suitable: the code can be intercepted by a malicious app.</li><li><strong>Resource Owner Password Credentials Flow</strong>. It requires credentials to be entered inside the application. This is not desirable if the application and service are not developed by the same team.</li><li><strong>Client Credentials Flow.</strong> Suitable for authorization of the client based on client_id, client_password. It does not require the user to enter credentials.</li><li><strong>Implicit Flow.</strong><a href="https://medium.com/oauth-2/why-you-should-stop-using-the-oauth-implicit-grant-2436ced1c926"><strong> </strong>Unsafe and outdated</a>.</li></ul><h3>📱How Authorization Code Flow with PKCE works</h3><p>For mobile clients, we recommend using Authorization Code Flow with the addition: <em>Authorization Code Flow with Proof Key for Code Exchange (PKCE). </em>Using this particular flow is important for the user safely application login. Let’s consider its features.</p><p>This flow is based on the basic Authorization Code Flow. First, let’s check its implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*aLG37RcuvUIeK8ZyyaZ56w.jpeg" /></figure><ol><li>The <em>User</em> clicks the Login button.</li><li>The <em>Mobile app</em> creates a link for authorization on the <em>Auth service</em> and opens it in the browser.</li><li>The <em>User</em> sees a screen with login/password fields.</li><li>The <em>User</em> enters the login and the password and grants access to the data.</li><li>The <em>Auth service</em> returns the authorization code to the <em>Mobile app</em> using a redirect. With the code, you won’t be able to get access to the required resources from the <em>App service </em>yet. <strong><em>In order for the redirect to be intercepted only by the application, custom schemes are usually used, not http(s). Otherwise, the code can also be intercepted by the browser. In this case, a disambiguation dialog appears.</em></strong></li><li>The <em>Mobile app</em> retrieves the code from the redirect URL and exchanges the code for a token. Additionally, client_id and client_secret can be passed.</li><li>The <em>Auth service</em> returns access_token, refresh_token.</li><li>The <em>Mobile app</em> uses the received token to communicate with the <em>App service</em>.</li></ol><p>When using Authorization Code Flow with PKCE, the scheme changes slightly. Differences are highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*cZcPz5tTHfe4rU_zU5E_kA.jpeg" /></figure><ol><li>The <em>User</em> clicks the login button.</li><li><strong>Code_verifier and code_challenge are generated and saved in the app.</strong> The generation process is described in<a href="https://datatracker.ietf.org/doc/html/rfc7636"> RFC-7636</a>.<br>code_challenge is derived from code_verifier, reverse transformation is not possible.</li><li><strong>The <em>Mobile app</em> creates an authorization link based on the generated code_challenge. The link is opened in the browser. At this point, the <em>Auth service</em> saves the code_challenge for the session. code_verifier remains only in the <em>Mobile app </em>memory and is not transmitted over the network</strong>.</li><li>The <em>User</em> sees a screen with login/password fields.</li><li>The <em>User</em> enters the login and the password and grants access to the data.</li><li>The <em>Auth service</em> returns the authorization code to the <em>Mobile app</em> using a redirect. Note that code_challenge is not returned from the server with the code. Only the <em>Auth service</em> and the <em>Mobile app</em> know about it.</li><li><strong>The <em>Mobile app</em> exchanges the code for a token. When exchanging, the <em>Mobile application</em> sends the code_verifier that was saved in step 2</strong>.</li><li><strong>The <em>Auth service</em> accepts code_verifier from the <em>Mobile app</em>. It derives the code_challenge from code_verifier and compares it with the code_challenge saved in step 3. If they match, the token is returned</strong>.</li><li>The <em>Auth service</em> returns access_token, refresh_token.</li><li>The <em>Mobile app</em> uses the received token to communicate with the <em>App service</em>.</li></ol><p>What would happen if code_verifier and code_challenge were not used?</p><h3>📱Intercepting auth by malicious app</h3><p>One of the OAuth implementations is using an external browser.</p><p>In this case, the code from <em>Auth service</em> is returned to the <em>Mobile app</em> using the system function: when a redirect to the URL inside the browser occurs, your <em>Mobile app</em> is opened if the app can handle the URL.</p><p>At the moment when the system is looking for an application to process the redirect URL, it is possible to intercept the redirect by a malicious application. An attacker can create an app that intercepts redirects like your app. All redirect data is leaked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3gVTRw1Xg65dqv1bb09EIg.jpeg" /><figcaption>Intercepting redirects by malicious app</figcaption></figure><p>That’s why you need to return an intermediate code in the redirect, not a token. Otherwise, the token will be available to malicious app.</p><p>When using the basic Authorization Code Flow, the malicious app can potentially get the code and exchange it for a token, similar to how it is done by your app (Real app). But using code_verifier and code_challenge makes malicious interception meaningless. Malicious app doesn’t know the code_verifier and code_challenge that were generated inside your app, and they aren’t returned in the redirect.</p><p>Without this data, the malicious application will not be able to exchange the code for a token.</p><p>Note that such an attack will not work if you use universal links (on ios) and applink (on android). To open a redirect link in the app, you need to put a json file with your app’s signature to the server.</p><p>But often we can’t add a json file to the server if we are using an external service. That’s why it can help not always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*zClBrqFvkYkl-i16w3-GOw.jpeg" /></figure><h3>📱 Implementation details 🔍</h3><p>How to open the login page?</p><p>The OAuth login page is a web page. There are the following ways to open it:</p><ul><li>WebView inside your application.</li><li>An external browser.</li><li>ChromeCustomTabs, SafariVC.</li></ul><p>When choosing a method, keep in mind that the main task of OAuth is to provide access without entering credentials inside the application process.</p><h4>1️⃣ WebView 🏜</h4><p>👍 <strong>Advantages:</strong></p><ul><li>You can customize the ui of the screen completely as you need.</li><li>The screen with WebView may be opened faster than the page in the browser: webview works inside your application process, without interprocess interaction. But in Android O webview rendering works in separate process.</li></ul><p>👎 <strong>Disadvantages:</strong></p><ul><li>WebView implementation is not secure in general, and some social networks, like<a href="https://developers.googleblog.com/2021/06/upcoming-security-changes-to-googles-oauth-2.0-authorization-endpoint.html"> Google</a>, do not allow this way of implementing OAuth. In practice, it is possible to hack this by replacing the user agent.<a href="https://developers.google.com/terms/api-services-user-data-policy#deceptive_or_unauthorized_use_of_google_api_services_is_prohibited"> But that doesn’t correspond to Google policy</a>, and you can’t do that.</li><li>The general problem is that WebView works within the application. The creator of a malicious application can inject between the user and the service in which the user logs in and intercept the password and the login. One of the goals of the OAuth protocol is to counter this.</li><li>WebView executes JS in the process of your application, which is not safe for the application itself. If you are using WebView inside your app, I recommend that you read<a href="https://www.securing.pl/en/webview-security-issues-in-android-applications/"> the setup tips for added security</a>.</li><li>WebView decreases UX. The user may have already been authorized in the browser, but WebView will not know about this, since WebView and the browser have splitted cookie storages.</li></ul><p>Due to the disadvantages, WebView is not acceptable option for implementing OAuth in a mobile application.</p><h4>2️⃣ Browser 🌐</h4><p>The second option is to open the page in an external browser installed on the device.</p><p>👍 <strong>Advantages:</strong></p><ul><li>Opening a page in the browser is very easy.</li><li>Your app has no control over your browser or opened webpage. This provides additional security for the user.</li><li>The browser saves the user’s cookies. This means that if the user was already logged in to the service inside the browser, he doesn’t have to re-enter credentials on OAuth.</li></ul><p>👎 <strong>Disadvantages:</strong></p><ul><li>Opening the browser is a heavy operation because we need to start an external process.</li><li>You cannot configure the browser UI, it opens in an external window.</li><li>When you open the browser, you leave the navigation stack of the app.</li></ul><p>Browser is an acceptable option for implementing OAuth in a mobile application but not the best.</p><h4>3️⃣ ChromeCustomTabs, SafariVC 📊</h4><p>ChromeCustomTabs (CCT) and SafariViewController (SafariVC), like the browser, make it easy to open web pages in your app.</p><p>👍 <strong>It eliminates drawbacks of WebView:</strong></p><ul><li>The attacker will not be able to intercept the data entered on the login page.</li><li>Data is available to the browser and CCT/SafariVC. Because cookie storage is same.</li><li>Note: starting with ios 11, data between browsers and different SafariVC sessions is no longer automatically shared. To implement this, you need to use<a href="https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession"> ASWebAuthenticationSession</a>.<br>Example:<a href="https://gist.github.com/MaxMyalkin/e30770d18f0201e4a68cafe23c3a3b2e"> GitHub Gist</a>.</li><li>JS is executed in an external process, this will secure your application.</li></ul><p>👍 <strong>The browser’s drawbacks are partially eliminated:</strong></p><ul><li><a href="https://developer.chrome.com/docs/android/custom-tabs/integration-guide/#warm-up-the-browser-to-make-pages-load-faster">CCT allows you to warm up the background</a>, which allows you to quickly load the page when it is opening.</li><li>An opened CCT does not reduce the priority of your application’s process because it may lead to process kill by the OS.</li></ul><p>There are limiter options for customizing the appearance:<a href="https://developer.chrome.com/docs/android/custom-tabs/integration-guide/"> CCT</a>,<a href="https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller#topics"> SafariVC</a>.</p><p>CCT was originally made only for Chrome. Now it is supported in different browsers. In addition to it, there is also TrustedWebActivity in Android. You can read more about them<a href="https://developer.chrome.com/docs/android/trusted-web-activity/"> on the official page</a>.</p><p>This is the best approach for opening an OAuth page. It eliminates almost all the drawbacks of the previous two approaches.</p><h3>🤷‍♂️ Redirect doesn’t work in Chrome</h3><p>As mentioned above, it is better to use a URI with custom scheme to redirect back to the app, so that the redirect is not intercepted by browsers.</p><p>While testing the implementation of OAuth in Android, we encountered that CCT with Chrome browser after successful authorization, did not redirect user into the app on some devices. There’s<a href="https://bugs.chromium.org/p/chromium/issues/detail?id=738724"> a bug in the tracker</a> for this.</p><p>The reason is simple. An<a href="https://chromium.googlesource.com/chromium/src/+/a1f331bf3aaa9c8f65c02bb38f14c5a81184d4ce/chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationHandler.java#320"> update</a> was made in Chrome browser that prevents you from following URL with custom scheme without user intent. This behavior blocks the user from getting into a malicious application.</p><p>To bypass this restriction, we made the web page that the browser redirects to after successful authorization. The webpage automatically tries to make a redirect inside the app. If this doesn’t happen, and Chrome has blocked the redirect, the user can click the enter button and go explicitly. Then Chrome does not block redirect because clicking is user intent. That approach works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*HPOLteaZBvZH5l-K8653Ag.png" /></figure><h3>🥬 Token refreshing</h3><p>With OAuth you need to remember about token refreshing.</p><p>This is usually similar to how to change a code to a access_token. You are requesting API service to get a token and specifying grant_type=refresh_token and refresh_token, which you received initially when logging in.</p><p>We are going to discuss implementation details in the example below.</p><h3>⭕️ Browser is missing</h3><p>Android, unlike iOS, may not have an installed browser. But if we are using CCT, we will need to make sure that the user has installed the browser with CCT protocol implementation.</p><p>In addition to Chrome, this feature is supported in SBrowser, Firefox, and all other modern browsers. But even if the user doesn’t have one, a regular browser opens.</p><p>Developing page shows <a href="https://developer.chrome.com/docs/android/custom-tabs/integration-guide/#how-can-i-check-whether-the-android-device-has-a-browser-that-supports-custom-tab">how to check browsers with CCT support</a>.</p><h3>🚪 Logout</h3><p>In application cases without OAuth, you need to clear tokens / cache files / databases when a user logouts.</p><p>If you use CCT/SafatiVC for OAuth, then the browser saves cookies of the authorized person. When you log in again, you will be automatically logged in to your first account again. It is not possible to clear cookies from the app directly, because the browser works inside a separate process with its own cookie storage. And access to it is prohibited from other apps.</p><h3>🔅 OAuth implementation options 🔆</h3><p>We checked OAuth flow for mobile apps and implementation details. Next step — select implementation option.</p><p>There are several options:</p><ul><li>Service SDK</li><li>Manual implementation</li><li>OAuth libraries</li></ul><h3>🛎 Service SDK</h3><p>Implementing OAuth logic with SDK dependency. E. g. you need FB OAuth and use <a href="https://developers.facebook.com/docs/android/getting-started/">Facebook SDK</a></p><p>👍 <strong>Pros:</strong></p><ul><li>simple implementation;</li><li>authorization via native apps is possible if they are installed. E.g. login through FB application.</li></ul><p>👎 <strong>Cons:</strong></p><ul><li>increasing external dependencies count, especially with a large number of external OAuth services;</li><li>there is no implementation control, if you will want to change something — you can’t.</li></ul><p>We are not going to consider using SDK in the current article, because this requires the SDK documentation research.</p><h3>✍️ Manual implementation</h3><p>Implementing OAuth logic manually within your own application using WebView or other implementations (CCT/SafariVC).</p><p>👍 <strong>Pros:</strong></p><ul><li>you get full implementation control</li></ul><p>👎 <strong>Cons:</strong></p><ul><li>you have to write your own code, maintain it and take into account manually the nuances discussed above.</li></ul><p>We are not going to consider manual implementation, because it is individual for each application and service. It option may be justified in complex mobile applications with large codebase and custom architecture.</p><h3>📚OAuth libraries</h3><p>There are many open source libraries for mobile OAuth.</p><p>Libraries should support the OAuth and OpenId protocols and allow communication with any services.</p><p>Examples:</p><ul><li><a href="https://github.com/openid/AppAuth-iOS">AppAuth IOS</a></li><li><a href="https://github.com/openid/AppAuth-Android">AppAuth Android</a></li><li><a href="https://github.com/auth0/Auth0.Android">Auth0 Android</a></li><li>When using this approach, you need to make sure that the authentication server is functioning according to the OAuth protocol, and you don’t have to hack the library to link it.</li><li>If you understand the library and know how it works, the OAuth implementation is quite simple. But it takes time.</li><li>The authorization implementation will be universal for different services, you do not have to connect additional dependencies and write a lot of code for each external service.</li><li>Note that the implementation of the library may not be completely convenient for using in your application. The approaches used to communicate with the library may differ from those adopted in your team, and you will need to write wrappers and bridges. Example: AppAuth library in Android uses AsyncTask, but in your app you use coroutines. But usually it is not problem.</li></ul><p>In the following part, we are going to discuss the OAuth implementation using the AppAuth library. There are several reasons for this:</p><ul><li>this is a fairly popular library;</li><li><a href="https://developers.google.com/identity/protocols/oauth2/native-app">it is recommended by Google for OAuth implementation</a>;</li></ul><p>it has both<a href="https://github.com/openid/AppAuth-Android"> Android</a> and<a href="https://github.com/openid/AppAuth-iOS"> iOS</a> implementations.</p><p>In the next chapter of article we will correctly implement OAuth in Android &amp; iOS. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d65aced9a7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/oauth-mobile-implementation-details-8d65aced9a7f">OAuth mobile implementation details</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>