React Native: Authentication with WebView
Tags: reactnative, webview, authentication, cookies
Published: 2020-01-13 03:27:59

A more interactive tutorial: https://getleaf.app/dsps301/reactnativeau-pvopbxhp

You have a web application with all your features built out and now it is time to build your mobile app. You find yourself writing out the same business logic over again and think, "hmm maybe there is a quicker way to initially implement features, to iterate faster?"

Good news, you can! 🎉

Using the power of web views, mobile applications can wrap login flows and authenticate users without having to rewrite the logic.

## React Native WebView
Let's get started with a powerful tool called `react-native-webview`.

Starting with a basic example that loads the login page.
```react
import React, { FunctionComponent } from 'react';
import { WebView } from 'react-native-webview';

const LoginWebView: FunctionComponent = () => (
  <WebView
    source={{ uri: 'https://mywebapp.com/login' }}
  />
);
```
Now the user can see the login page and go down any of the app's auth flows.

Features supported:
✅ Login
✅ Sign Up
✅ Forgot Password

## URL Param Tokens
Some authentication flows will redirect to a URL containing the user's access token as a URL param.

Taking advantage of `react-native-webview`'s prop `onNavigationStateChange`, we can watch the URL changes and act accordingly.

We will detect when the token is in the URL, then parse it out so it can be used in the mobile app.

```react
import React, { FunctionComponent } from 'react';
import { WebView, WebViewNavigation } from 'react-native-webview';

const onNavigationStateChange = (navigationState: WebViewNavigation) => {
  const url = navigationState.url;

  // parseURLParams is a pseudo function.
  // Make sure to write your own function or install a package
  const params = parseURLParams(url);

  if (params.token) {
    // Save token for native requests & move to the next screen
  }
};

const LoginWebView: FunctionComponent = () => (
  <WebView
    source={{ uri: 'https://mywebapp.com/login' }}
    onNavigationStateChange={onNavigationStateChange}
  />
);
```
Now the user is authenticated and the token can be used in your app!

Features supported:
✅ URL Param Token-based Auth

## Cookies Based Auth
For more complex auth flows, you may need several cookies to authenticate a user.

Taking advantage of `react-native-webview`'s prop `onMessage`, we can send the document's cookies to the native code.

Every time `navigationStateChange` is triggered, we will inject a script using `injectJavaScript` that returns cookie information for `onMessage` to process.
```react
import React, { createRef, FunctionComponent } from 'react';
import { WebView, WebViewNavigation } from 'react-native-webview';

// Send the cookie information back to the mobile app
const CHECK_COOKIE: string = `
  ReactNativeWebView.postMessage("Cookie: " + document.cookie);
  true;
`;

const onNavigationStateChange = (navigationState: WebViewNavigation) => {
  ...

  // Check cookies every time URL changes
  if (webViewRef.current) {
    webViewRef.current.injectJavaScript(CHECK_COOKIE);
  }
};

const onMessage = (event: NativeSyntheticEvent<WebViewMessage>) => {
  const { data } = event.nativeEvent;

  if (data.includes('Cookie:')) {
    // process the cookies
  }
};

let webViewRef = createRef<WebView>();
const LoginWebView: FunctionComponent = () => (
  <WebView
    ref={webViewRef}
    source={{ uri: 'https://mywebapp.com/login' }}
    onNavigationStateChange={onNavigationStateChange}
    onMessage={onMessage}
  />
);
```

Now the application has cookies for future requests.

Features Supported:
✅ Cookie Based Auth

### iOS Quirk
WKWebView stores session cookies on the device. It will not be returned in the `CHECK_COOKIE` script we used above.

To get around this we need to use `@react-native-community/react-native-cookies` to extract the cookies from the device cookie manager.

We need to set the `sharedCookiesEnabled` prop to true. This tells WebView to save the cookies onto the native cookie manager.
```react
import React, { createRef, FunctionComponent } from 'react';
import { WebView, WebViewNavigation } from 'react-native-webview';
import CookieManager from '@react-native-community/react-native-cookies';

// Send the cookie information back to the mobile app
const CHECK_COOKIE: string = `
  ReactNativeWebView.postMessage("Cookie: " + document.cookie);
  true;
`;

const onNavigationStateChange = (navigationState: WebViewNavigation) => {
  ...

  // Check cookies every time URL changes
  if (webViewRef.current) {
    webViewRef.current.injectJavaScript(CHECK_COOKIE);
  }
};

const onMessage = async (event: NativeSyntheticEvent<WebViewMessage>) => {
  const { data } = event.nativeEvent;

  if (data.includes('Cookie:')) {
    // process the cookies
    const storedCookies = await CookieManager.get(
      'https://mywebapp.com/login', 
      true
    );
};

let webViewRef = createRef<WebView>();
const LoginWebView: FunctionComponent = () => (
  <WebView
    ref={webViewRef}
    source={{ uri: 'https://mywebapp.com/login' }}
    onNavigationStateChange={onNavigationStateChange}
    onMessage={onMessage}
    sharedCookiesEnabled
  />
);
```
Features:
✅ iOS Support


## Conclusion
Web views can be used in very creative ways to build mobile applications; especially, if you want to iterate quick. 

Let me know if there are other ways of authenticating through web views or a different type of authentication that you want to be seen done!

Leave a comment if this was helpful or have any questions!

You can find me on Twitter [@safaiyeh](https://twitter.com/safaiyeh)

or maintaining [react-native-webview](https://github.com/react-native-community/react-native-webview) and [@react-native-community/react-native-cookies](https://github.com/react-native-community/react-native-cookies).

Keep Building!