Search code examples
react-nativeoauthexpogoogle-oauthexpo-web

Stuck on openAuthSessionAsync - How to Close Browser After Successful Google OAuth Login?


I'm currently working on a React Native app where I'm using Google OAuth for user authentication. I'm leveraging the openAuthSessionAsync method from the Expo AuthSession API to handle the authentication flow. The login process works fine, and I can successfully retrieve the session ID. However, I'm stuck on how to close the browser window once the login is completed.

Here is the relevant part of my code:

const signIn = async () => {
    const frontEndUrl = getBaseUrl();
    const result = await Browser.openAuthSessionAsync(
        `${frontEndUrl}/auth/google?mobile=true`,
        `${frontEndUrl}`
    ;
    console.log(result.type);

    if (result.type !== "success") return;
    const url = Linking.parse(result.url);
    const sessionID = url.queryParams?.session_id?.toString() ?? null;
    if (!sessionID) return;
    await SecureStore.setItemAsync("session_id", sessionID);
};

I've followed the guide from Lucia Auth Guidebook on GitHub OAuth with Expo, but it doesn't mention how to close the browser after authentication or address issues with not getting any result.

Issues I'm Facing:

Browser Window Not Closing: After a successful login, the browser window remains open.

No Result Returned: The result object from openAuthSessionAsync does not contain any data, making it impossible to proceed with the authentication flow.

I've searched through the Expo and React Native documentation but haven't found a solution yet.

Is there a way to close the browser window programmatically after a successful login using openAuthSessionAsync?

Or simply ensure that the openAuthSessionAsync method returns the expected result so I can proceed with my authentication flow?

Any help or guidance would be greatly appreciated!

Thank you in advance!

Additional Context:

React Native Version: 0.74.2 Expo SDK Version: 51 Platform: Android Github Repo: RecordScratch


Solution

  • I was able to fix the problem.

    I simply needed to provide a deep link from the Expo browser to the mobile app. The result would return success once I set up the redirect URL to the deep link provided by the Expo browser.

    So

    const result = await Browser.openAuthSessionAsync(
            `${frontEndUrl}/auth/google?mobile=true`,
            `${frontEndUrl}`);
    

    Simply became

    const result = await Browser.openAuthSessionAsync(
            `${frontEndUrl}/auth/google?mobile=true`,
            `exp://192.168.2.100:8081`);
    

    And then on my backend Authentication handler, I had to redirect to exp://192.168.2.100:8081 once completed.

    https://docs.expo.dev/guides/deep-linking/