0

Based on this answer I tried to retain my session in IOS and even though I am passing the cookies back with the request, I am still coming back when I exit and re-open the app, the difference from the above link is I am using django and its sessions

export default class App extends Component {
    constructor(props) {
        super(props);
        this.currentUrl = '';
        this.myWebView = React.createRef();
        this.state = {
            isReady: false,
            cookiesString: '',
            userAgent: '',
        };
    }

    UNSAFE_componentWillMount() {
        // CookieManager.clearAll();
        this.provideMeSavedCookies()
            .then(async (savedCookies) => {
                let cookiesString = this.jsonCookiesToCookieString(savedCookies);
                const sessionid = await AsyncStorage.getItem('sessionid');
                if (sessionid) {
                    cookiesString += `sessionid=${sessionid};`;
                }
                DeviceInfo.getUserAgent().then((userAgent) => {
                    this.setState({userAgent: userAgent, cookiesString, isReady: true});
                });
            })
            .catch((e) => {
                this.setState({isReady: true});
            });
    }

    onLoadEnd = () => {
        let successUrl = `${domain}`;
        if (this.currentUrl === successUrl) {
            CookieManager.getAll().then((res) => {
                console.log('RES');
                console.log(res)
                AsyncStorage.setItem('savedCookies', JSON.stringify(res));
                if (res.sessionid) {
                    AsyncStorage.setItem('sessionid', res.sessionid.value);
                }
            });
        }
    };

    jsonCookiesToCookieString = (json) => {
        let cookiesString = '';
        for (let [key, value] of Object.entries(json)) {
            cookiesString += `${key}=${value.value}; `;
        }
        return cookiesString;
    };

    onNavigationStateChange = (navState) => {
        this.currentUrl = navState.url;
    };


    provideMeSavedCookies = async () => {
        try {
            let value = await AsyncStorage.getItem('savedCookies');
            if (value !== null) {
                return Promise.resolve(JSON.parse(value));
            }
        } catch (error) {
            return {}
        }
    };

    render() {
        const {userAgent, cookiesString, isReady} = this.state;
        return (
            <SafeAreaView style={{ flex:1 }}>
                {isReady && <WebView
                    ref={this.myWebView}
                    source={{
                        uri: `${domain}`,
                        headers: {
                            'Cookie': cookiesString,
                            'Connection': 'keep-alive',
                            'Cache-Control': 'max-age=0',
                            'User-Agent': userAgent
                        },
                    }}
                    useWebView2={true} # this is just to test
                    cacheEnabled={false}
                    incognito={false}
                    scalesPageToFit
                    useWebKit
                    onLoadEnd={this.onLoadEnd}
                    onNavigationStateChange={this.onNavigationStateChange}
                    sharedCookiesEnabled
                    javaScriptEnabled={true}
                    domStorageEnabled={true}

                />}
                {!isReady &&
                    <View><Text>Loading...</Text></View>
                }
            </SafeAreaView>
        );
    }
}

This is my cookiesString

csrftoken=6dkeV4w5qcUbAnM1IvUoIt7EhZVScsSbj4bkWHJLRXQWyk3zy40eSREqaeE0mpaT; sessionid=x2x65ksaz9k9izw756vnie4dmlgdx1zk; sessionid=x2x65ksaz9k9izw756vnie4dmlgdx1zk;

My request and response headers in PC's browser enter image description here

Prabhakaran
  • 3,900
  • 15
  • 46
  • 113

1 Answers1

0

you can Django csrftoken by using injectedJavaScript in WebView and assign the CSRF Token to WebView

 const csrfToken = "your-csrf-token-value";
 const jsCode = `
 var csrfToken = "${csrfToken}";
 document.querySelector('meta[name=csrf-token]').setAttribute('content', csrfToken);`


<WebView
   source={{ uri: 'your-django-app-url' }}
   injectedJavaScript={jsCode}
   sharedCookiesEnabled={true}
/>

You might need to add this meta tag to your Django app <meta name="csrf-token" content="{{ csrf_token }}">

then for Javascript Form submission add this to use csrf

 const jsCode = `
 var csrfToken = document.querySelector('meta[name=csrf token]').getAttribute('content');
 // Attach csrfToken to your AJAX requests if you use it`;
Soliman
  • 332
  • 3
  • 11