Implementing Auth0 in React Native / Expo App

Here is the solution I used, it uses expo’s way of doing things.

The steps used in this solution are to:

  1. Import the AuthSession module from expo
  2. Set your auth0Domain and ClientID as available variables (although I’d use a more secure solution like environment variables in production)
  3. Use the Expo AuthSession module to set a redirect url and set the authentication URL
  4. Use the Expo AuthSession module to initiate the redirect process
  5. Store the resulting token as you see fit (in this case, in the Redux store)
  6. Allow a user component to trigger the process (we wrapped steps 2-5 in a component method)

Hope it helps!

import { AuthSession } from ‘expo’;
const auth0Domain = ‘https://yourdomain.auth0.com’;
const auth0ClientId = ‘yourid’;
class Auth0LoginContainer extends React.Component<Props, State> {

_loginWithAuth0 = async () => {
    const redirectUrl = AuthSession.getRedirectUrl();
    let authUrl = `${auth0Domain}/authorize` + toQueryString({
        client_id: auth0ClientId,
        response_type: 'token',
        scope: 'openid profile email',
        redirect_uri: redirectUrl,
    });
    console.log(`Redirect URL (add this to Auth0): ${redirectUrl}`);
    console.log(`AuthURL is:  ${authUrl}`);
    const result = await AuthSession.startAsync({
        authUrl: authUrl
    });

    if (result.type === 'success') {
        console.log(result);
        let token = result.params.access_token;
        this.props.setToken(token);
        this.props.navigation.navigate("Next Screen");
    }
};

render() {
    return (
        <Login
            navigation={this.props.navigation}
            onLogin={() => this._loginWithAuth0()}
        />
    );
}

}

2 Likes