5
votes

My WebView should display a web page that has a cookie authentication. The page expects a session-id cookie acquired on login. To authenticate I send the login request to the website using fetch().

When the login is successful I can see that proper cookies are received. On success, I'm starting the WebView.

It works perfectly on Android but not on iOS.

Yesterday I tried a lot of different approaches suggested on SO, like getting cookies manually with react-native-cookies, but nothing helps.

Below is a sample component that does the same thing as my app does. I thought that the problem may be in the configuration of my app, so I created this extremely simple example and it has the same problem.

export default class App extends Component {
constructor(props) {
  super(props)
  this.state = {
    response: null,
  }
}

async componentDidMount() {
  const response = await this.logIn()
  console.log('LogIn completed', response)
  this.setState({
      response: response
    })
}

async logIn() {
  const url = 'myurl/login?email=email&password=password'
  const headers = {'MyHeader': 'Header text'}
  try {
    let response = await fetch(url, {
      method: 'POST',
      headers: headers,
      // credentials: 'same-origin',
      credentials: 'include',
    })
    return Promise.resolve(response)
  } catch (error) {
    return Promise.reject(error)
  }
}

render() {
  const url = 'myurl/dashboard'
  const headers = {'MyHeader': 'Header text'}
  return (
    <WebView source = {{
      uri: url,
      headers: headers
    }}
    />
  )
}
}

I tested it on iOS 9 and iOS 11 simulators, and on an iOS 11 device.

To sum up the question: Why cookies I've got with fetch aren't passed to WebView on iOS only.

2

2 Answers

2
votes

Use property sharedCookiesEnabled={true} in webView. It's working in my case.

1
votes

I've found the problem. The lack of cookies was only the consequence of the wrong authorisation caused by wrong 'User-Agent' header. I was trying to pass User-Agent in the WebView headers. It works fine on android but requires a workaround for iOS. To set the User-Agent header on iOS you need to change UserDefaults from the AppDelegate.

NSString *userAgent = @"YourUserAgentString";
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

Thanks to this answer: https://stackoverflow.com/a/37917932/3055378