androidiosreact-nativecookieswebview

React Native - Use cookies to authenticate in WebView


So I've been provided a couple of API's for a React Native application. One endpoint is for authentication and it returns a cookie which allows access to other API's.

The cookie has the following structure:

{"auth":"ok","instance":"private","cookies":{"SSOsess":"300|c6dc6d70vfvbf0891004364665f24b77","RTBk":"300|451706342c67a37dfe5dede0b5d22469","ph03RPNCiscoASA":"application.api.urlweb.com","ph04RPNCiscoASA":"application.client.urlweb.com"}}

After a bit of formatting the cookie is ready to be sent and looks like this:

SSOsess=300%7Cc6dc6d70vfvbf0891004364665f24b77; RTBk=300%7C451706342c67a37dfe5dede0b5d22469;
ph03RPNCiscoASA=application.api.urlweb.com;
ph04RPNCiscoASA=application.client.urlweb.com;

The are some WebView's inside the React Native application that access some restricted parts of a website that uses some of the API's initially provided.

How can I send the cookie to the WebView? I know React Native has some attributes that could be used to inject cookies into the WebView such as injectedJavaScript or injectedJavaScriptBeforeContentLoaded but what exactly should those attributes contain?

I've tried sending it the following way but it does not work:

<WebView source={{ uri: 'http://urlweb.com' }}
               style={{width: 600, height: 400}}
               injectedJavaScriptBeforeContentLoaded={jsInjectedCode}
/>

where

jsInjectedCode = 'document.cookie = '+'SSOsess=300%7Cc6dc6d70vfvbf0891004364665f24b77; RTBk=300%7C451706342c67a37dfe5dede0b5d22469;
    ph03RPNCiscoASA=application.api.urlweb.com;
    ph04RPNCiscoASA=application.client.urlweb.com;'

Solution

  • you can pass cookies string into Cookie inside header like this DOCS

    import React, {Component} from 'react';
    import {StyleSheet, View} from 'react-native';
    import {WebView} from 'react-native-webview';
    
    export default class App extends Component {
      render() {
        const cookiesString="cookie1=asdf; cookie2=dfasdfdas";   //here you can put your cookies
        return (
          <View style={styles.container}>
            <WebView
              source={{
                uri: `${domain}`,
                headers: {
                  Cookie: cookiesString,
                },
              }}
              style={styles.WebViewStyle}
            />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#FFF',
      },
      WebViewStyle: {
        flex: 1,
        resizeMode: 'cover',
      },
    });