React Native cookie-based authentication
Tags: react, javascript
Published: 2020-08-03 08:11:37

<!-- wp:paragraph -->
<p>User authentication is a single-handedly most required feature when building a modern web or mobile apps. It allows verifying users, user sessions, and most importantly it provides the base for implementing user authorization (roles and permissions).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Basically, you develop a login screen and allow the user to input their username/email and appropriate password and send a request to the server. If the server responds positively, that's it. Your user is logged in. But server returned one more thing: some kind of user identification you need to pass together with other requests to access certain data etc. Also, when the user closes the app without logging out, thanks to this we can keep him logged in and skip the login step every time the user opens the app.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It is either token-based authentication or session-based authentication. This diagram describes the main differences between the two:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"width":576,"height":293} -->
<figure class="wp-block-image is-resized"><img src="https://s3.us-west-2.amazonaws.com/secure.notion-static.com/6728ec52-d84b-4ad9-a189-105f8585c86d/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20200603%2Fus-west-2%2Fs3%2Faws4_request&amp;X-Amz-Date=20200603T093335Z&amp;X-Amz-Expires=86400&amp;X-Amz-Signature=f48eb4156aa961142cec31d0f3c88ba5dccd1fe8b742c32eba7390e45f69ecbf&amp;X-Amz-SignedHeaders=host&amp;response-content-disposition=filename%20%3D%22Untitled.png%22" alt="" width="576" height="293"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"customFontSize":12} -->
<p style="font-size:12px"><em>Chart credit: </em><a href="https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide"><em>https://dzone.com/articles/cookies-vs-tokens-the-definitive-guide</em></a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you can see, in cookie-based authentication, after successful login, the server creates the session and return sessionId value as Cookie. Subsequent requests contain that cookie with sessionId which is verified against sessionId on the server to determine if the session is valid.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>On the other hand, we have token-based authentication. After successful login server returns signed token. That token is then usually stored in local storage. Subsequent requests are sent together with the saved token in the Authorization header. The server decodes token and if it is valid, process the request.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Without further due, like the title states - this article will go through cookie-based authentication in React Native because it is not as straightforward as you may think.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>The Problem</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As you know, React Native relies on the native (Android and iOS) APIs written in Java and Objective-C. You may think the cookie usage is as straightforward as using it within the browser but unfortunately, it isn't.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":9266} -->
<figure class="wp-block-image"><img src="https://locastic.com/wp-content/uploads/2020/06/Screenshot-2020-06-02-at-10.47.51.png" alt="" class="wp-image-9266"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Native networking APIs are saving the cookies by default and it may seem perfectly okay at the beginning, but after some time and few requests made, requests can become inconsistent causing the server to deny the access because the cookies we sent were invalid even though there is nothing wrong with them when they initially were passed along the request.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>The Solution</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The first thing that came to my mind is to take the cookie management in to my own hands by simply storing them on the device (eg. Async Storage)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now the flow goes like this:</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://s3.us-west-2.amazonaws.com/secure.notion-static.com/6058a708-5595-4b5e-ba47-1fd15a58e05e/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20200603%2Fus-west-2%2Fs3%2Faws4_request&amp;X-Amz-Date=20200603T093825Z&amp;X-Amz-Expires=86400&amp;X-Amz-Signature=df7ef8224cdd40e09126714b2928c1aca4ebd6cccecee2263e529f1f344c5c1c&amp;X-Amz-SignedHeaders=host&amp;response-content-disposition=filename%20%3D%22Untitled.png%22" alt=""/></figure>
<!-- /wp:image -->

<!-- wp:list {"ordered":true} -->
<ol><li>after successful login, the server responds with the status and cookies</li><li>cookies are saved on the device (Async Storage)</li><li>each subsequent request's Header is populated with the cookie from device storage</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>And I thought this is the final solution. EZ right? But let's see what the flow really looks like now:</p>
<!-- /wp:paragraph -->

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://s3.us-west-2.amazonaws.com/secure.notion-static.com/708df740-6047-43df-9c3e-0a77a77fddfb/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20200603%2Fus-west-2%2Fs3%2Faws4_request&amp;X-Amz-Date=20200603T093834Z&amp;X-Amz-Expires=86400&amp;X-Amz-Signature=577245ff403416c6851949a88b27365df003dc98dfdf44c9b2213bb3435c10ba&amp;X-Amz-SignedHeaders=host&amp;response-content-disposition=filename%20%3D%22Untitled.png%22" alt=""/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>It was working fine for a while but then the same problems started to occur and I was at the starting point again. As mentioned above, React Native has its own cookie management and now I implemented my own on top of it. Naturally, native API interfered with my implementation and won every time, overriding the cookie I sent with its own and causing the same problems to appear.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>NOTE: I'm not 100% sure yet this is what is happening on the native side.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After some research, I stumbled on the <a href="https://github.com/joeferraro/react-native-cookies">react-native-cookies</a>. It's a cookie management library for React Native and lets you manage cookies natively. Now there is actually a way to manipulate native cookie management, the approach with storing the cookie on the device can be further improved.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As already mentioned, native cookie management interfered with the stored cookies. So let's completely remove native cookies and work just with the ones stored on the device. The easiest way would be to just clean up the cookies stored natively.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's where the above-mentioned library comes into play:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import CookieManager from 'react-native-cookies'
import AsyncStorage from '@react-native-community/async-storage';

const client = async () => {
	await CookieManager.clearAll() //clearing cookies stored 
                                       //natively before each 
                                       //request
	const cookie = await AsyncStorage.getItem('cookie')
	return await fetch('api/data', {
		headers: {
			'cookie': cookie
		}
	})
}
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>With natively stored cookies cleaned up before each request, it's certain that the only cookies that are passed along the request are the ones stored manually on the device. Using this simple fix there are no more cookies interfering with each other and the main benefit is consistent sessions while using the app.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Wrap up</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I spent a significant amount on time wrestling with this issue because it wasn't so straight forward to figure out what seems to be the problem. I decided to write it down so you don't have to.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I think it's worth mentioning to say this is not the only possible solution to this problem because the problem itself is not fully investigated.  There are also solutions without using any library which is described in this <a href="https://www.syntx.io/react-native/cookie-management-in-react-native/">article</a>.</p>
<!-- /wp:paragraph -->