Supabase Google auth integration with Capacitor (React) for iOS
Asked Answered
E

2

6

I am trying to integrate Supabase Google Auth into my Hybrid app built with Capacitor.

It is working fine for web, but I am not able to get it working for iOS.

There isn't any documentation around this as well.

Opening in browser and failing

I've tried to change the redirect URL as well

supabase?.auth.signInWithOAuth({
                provider: "google",
                options: Capacitor.isNativePlatform()
                ? {
                    redirectTo: "capacitor://localhost",
                }
                : {},
});

This brings me back to the app, but doesn't log me in

Coming back to app but not logging in

Elle answered 8/3, 2023 at 10:23 Comment(1)
I'm unfortunately not familiar with capacitor, but maybe you can find a solution within this React Native example: github.com/supabase/supabase/discussions/…Hutchings
M
1

with capacitor you will have to setup a session manually for mobile for ex redirect to a new page that will handle that

myapp://confirmation

then in this new page

useEffect(() => {
    const hash = window.location.hash;
    const parts = hash.replace('#', '').split('&');
    for (const item of parts) {
        var [key, value] = item.split('=');
        if (key === 'access_token') setAccess(value);
        if (key === 'refresh_token') setRefresh(value);
    }
}, []);
useEffect(() => {
    if (!access || !refresh) return;
    const setSessionfunc = async (access_token: string, refresh_token: string) => {
        await supabase.auth.setSession({ access_token, refresh_token });
        router.push('/');
    };
    setSessionfunc(access, refresh);
}, [access, refresh]);

once the session is set you will be redirected to the home page

keep in mind also that supabase session uses cookies so you will need to add this in your capacitor.config.js

plugins: {
    CapacitorCookies: {
      enabled: true
    } 
}

good luck

Margitmargo answered 28/4, 2023 at 16:35 Comment(2)
How are you opening the browser window to start the google auth process?Levana
myapp://confirmation What URL is this?Pokeberry
P
0

My solution was to listen to the app returning from the authentication like follows:

import { App } from '@capacitor/app'
…
App.addListener('appUrlOpen', async (event) => {

    if (event.url.includes('/auth/v1/callback')) {
        const url = new URL(event.url);
        const fragment = url.hash.substring(1);
        const params = new URLSearchParams(fragment);const accessToken = params.get('access_token'); // Fetch access_token from the URL fragment
        const refreshToken = params.get('refresh_token'); // Fetch access_token from the URL fragment

        if (accessToken) {
            try {
                // Log current session before setting the new one
                const { data: currentSession, error: getSessionError } =
                    await supabase.auth.getSession();
                if (getSessionError) {
                    console.error('Error getting current session:', getSessionError.message);
                } else {
                    console.log('Current Session:', currentSession);
                }
                const { user, session, error } = await supabase.auth.setSession({
                    access_token: accessToken,
                    refresh_token: refreshToken
                });
                if (error) {
                    console.error('Error setting session:', error.message);
                } else {
                    console.log('New Session:', session);
                    console.log('User:', user);
                        // My Svelte store
                    _session = session;
                    if (user) {
                        console.log('has user', user);
                        // Update application state to reflect authenticated user
                        _user = user;

                    } else {
                        console.error('User is undefined after setting session');
                    }
                }
            } catch (error) {
                console.error('Error during setSession call:', error);
            }
        } else {
            console.error('Access token not found in URL fragment');
        }
    }
});
Pokeberry answered 30/6 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.