AWS Amplify Auth Login from React Native Webview on React Native

Viewed 361

I’m working on a React Native app that loads the example.com in a webview. I was wondering if it’s safe to use postMessage to pass username and password to React Native from the React Native webview. Do you think it’s okay or it's not safe?

This is the web app(example.com) sending username and password to React Native enter image description here

And this is React Native <WebView onMessage={m => this._onMessage(m)} /> to receive that username and password to Authenticate user. enter image description here

Seems like it will work but not sure if it’s safe. If not, is there a way to authenticate user in React Native from React Native webview?

1 Answers

According to MDN the postMessage method is safe, but please refer to security concern section.

You might send user session instead of username/password pair.

Your code would look like this:

// in webb app
const sendSession = async() => {
  const session = await Auth.currentSession()
  const data = {
    idToken: session.getIdToken().getJwtToken(),
    accessToken: session.getAccessToken().getJwtToken(),
    refreshToken: session.getRefreshToken().getToken(),
  }
  window.ReactNativeWebView?.postMessage(JSON.stringify(data))
}

// in mobile app
const _onMessage = (event) => {
  const data = JSON.parse(event.nativeEvent.data)
  const {
    idToken,
    accessToken,
    refreshToken
  } = data
  const userPool = new CognitoUserPool({
    UserPoolId: 'UserPoolId',
    ClientId: 'ClientId',
  })
  const cognitoIdToken = new CognitoIdToken({
    IdToken: idToken,
  })
  const cognitoAccessToken = new CognitoAccessToken({
    AccessToken: accessToken,
  })
  const cognitoRefreshToken = new CognitoRefreshToken({
    RefreshToken: refreshToken,
  })
  const username = cognitoIdToken.payload['cognito:username'] // or whatever you need to get from playload as a username
  const user = new CognitoUser({
    Username: username,
    Pool: userPool,
  })
  user.setSignInUserSession(
    new CognitoUserSession({
      AccessToken: cognitoAccessToken,
      IdToken: cognitoIdToken,
      RefreshToken: cognitoRefreshToken,
    }),
  )
}
Related