bug: signInWithCredential() generates CORS error on "capacitor://localhost" on iOS

See original GitHub issue

Plugin(s): @capacitor-firebase/authentication

Platform(s): iOS

Current behavior: When following the steps documented here for signing into Firebase JavaScript SDK, calling signInWithCredential generates a CORS error saying capacitor://localhost is not allowed.

[Log] Result of FirebaseAuthentication.signInWithGoogle(): โ€“ {credential: {accessToken: [REDACTED], providerId: "google.com", idToken: [REDACTED]}} (main.12648797.js, line 2)
[Error] TypeError: undefined is not an object (evaluating 'gapi.iframes.getContext')
	callback (main.12648797.js:2:216096)
	(anonymous function) (api.js:22:487)
	ka (api.js:15:704)
	B (api.js:22:471)
	(anonymous function) (api.js:23)
	(anonymous function) (api.js:23:113)
	Global Code (cb=gapi.loaded_0:1)
[Error] Error: A`capacitor
	(anonymous function) (api.js:23:599)
	(anonymous function) (api.js:22:487)
	ka (api.js:15:704)
	B (api.js:22:471)
	(anonymous function) (api.js:23)
	(anonymous function) (api.js:23:113)
	Global Code (cb=gapi.loaded_1:1)
[Error] Cross-origin redirection to http://developers.google.com/ denied by Cross-Origin Resource Sharing policy: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin. Status code: 301
[Error] XMLHttpRequest cannot load https://apis.google.com/_/jserror?script=https%3A%2F%2Fapis.google.com%2F_%2Fscs%2Fabc-static%2F_%2Fjs%2Fk%3Dgapi.lb.en.z9QjrzsHcOc.O%2Fm%3Dgapi_iframes%2Frt%3Dj%2Fsv%3D1%2Fd%3D1%2Fed%3D1%2Frs%3DAHpOoo8359JQqZQ0dzCVJ5Ui3CZcERHEWA%2Fcb%3Dgapi.loaded_0%3Fle%3Dscs&error=A%60capacitor&line=180 due to access control checks.
[Error] Failed to load resource: Cross-origin redirection to http://developers.google.com/ denied by Cross-Origin Resource Sharing policy: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin. Status code: 301 (jserror, line 0)

Expected behavior: The call to signInWithCredential should succeed.

Steps to reproduce:

Related code:

import { FirebaseAuthentication } from '@capacitor-firebase/authentication'
import {
   getAuth,              
   GoogleAuthProvider,
   signInWithCredential,
} from 'firebase/auth'

const signInWithGoogle = async () => {
  const result = await FirebaseAuthentication.signInWithGoogle()
  console.log("Result of FirebaseAuthentication.signInWithGoogle():", result)
  const credential = GoogleAuthProvider.credential(result.credential?.idToken)
  const auth = getAuth()
  const firebaseResult = await signInWithCredential(auth, credential)
  // This is never reached
  console.log("Firebase -> signInWithCredential", firebaseResult, auth, credential)
}

Other information:

Iโ€™m attempting to solve a problem where Firestore users are only authenticated when on the Ionic web platform, not on iOS, which effectively means read-only access to my Firestore database. My reading suggests that I need to make sure the user is signed in to both layers (native & web), but when I attempted that, I hit this CORs error.

Capacitor doctor:

๐Ÿ’Š   Capacitor Doctor  ๐Ÿ’Š 

Latest Dependencies:

  @capacitor/cli: 4.3.0
  @capacitor/core: 4.3.0
  @capacitor/android: 4.3.0
  @capacitor/ios: 4.3.0

Installed Dependencies:

  @capacitor/android: not installed
  @capacitor/cli: 4.3.0
  @capacitor/ios: 4.3.0
  @capacitor/core: 4.3.0

[success] iOS looking great! ๐Ÿ‘Œ

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

4reactions
maxbarrycommented, Oct 9, 2022

Aha! Yes, this worked, and led me to https://github.com/firebase/firebase-js-sdk/issues/5019#issuecomment-1213244332 which I believe is my bug. Signing in & out is now working on both web & device, which means signed-in users are authenticated when they make database write/update requests to the Firestore Cloud DB. Hooray! Thank you so much.

So my firebase.js file now contains:

import { initializeApp, getApp } from "firebase/app"
import { Capacitor } from "@capacitor/core"
import { getAuth, initializeAuth, indexedDBLocalPersistence } from "firebase/auth"

const firebaseApp = initializeApp(config)

let auth
export function getFirebaseAuth() {
  if (!auth) {
    if (Capacitor.isNativePlatform()) {
      auth = initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })
    } else {
      auth = getAuth()
    }
  }
  return auth
}

export default const firebaseApp

For signing in, my Login.js contains:

import { FirebaseAuthentication } from '@capacitor-firebase/authentication'
import { GoogleAuthProvider, signInWithCredential } from 'firebase/auth'
import { getFirebaseAuth } from './firebase'

const signInWithGoogle = async () => {
  const result = await FirebaseAuthentication.signInWithGoogle()
 
  const credential = GoogleAuthProvider.credential(result.credential?.idToken)
  const auth = getFirebaseAuth()
  await signInWithCredential(auth, credential)

  return result.user
}

To get signing out to work, I needed to replace FirebaseAuthentication.signOut() with this:

import { signOut } from 'firebase/auth'
import { getFirebaseAuth } from './firebase'

function signMeOut() {
  const auth = getFirebaseAuth()
  signOut(auth)
}

And my App.js listens for user changes:

import { getFirebaseAuth } from './firebase'

useEffect(() => {
    getFirebaseAuth().onAuthStateChanged(user => {
        if (!result) {
            setUser(null)
        } else {
            setUser({ ...user })
        }
    })

    async function getCurrentUser() {
        const { user } = await FirebaseAuthentication.getCurrentUser()
        if (user) {
            setUser(user)
        }   
    }
    getCurrentUser()

}, [ setUser ])
1reaction
robingenzcommented, Oct 10, 2022

Great, thanks for sharing. In this case I will close this issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

bug: firebase v9 not working on iOS ยท Issue #5531 - GitHub
That's a CORS error, should be fixed on the server, there is nothing we can do from Capacitor side. If it was working...
Read more >
CORS problem only over https Safari 11.0.3 - Apple Developer
It affects only POST requests (GET and OPTIONS works fine) on Safari over HTTPS. [Error] Origin [origin] is not allowed by Access-Control-Allow-ย ...
Read more >
CORS Errors: Cross-Origin Resource Sharing - Ionic Framework
CORS errors happen in web apps if requests are made and servers don't return ... For example, apps running in Capacitor have capacitor://localhost...
Read more >
How to fix CORS issue when using capacitor for an ios app?
I tried on ios and it gives a CORS error saying capacitor://localhost is not in the trusted origins, I tried to add using...
Read more >
3 Ways to Fix the CORS Error โ€” and How the Access-Control ...
Fix one: install the Allow-Control-Allow-Origin plugin. The quickest fix you can make is to install the moesif CORS extension .
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found