Search code examples
javascriptlocalhostgoogle-oauthgoogle-signin

Google auth fails using new Google identity sevices method on local http non-localhost domain


In migrating from Google sign in to the new Google identity services (ref: https://developers.google.com/identity/gsi/web/guides/migration) opening the Google auth prompt fails locally since my site does not use localhost as the domain. I could not find any specific documentation that might indicate this is a requirement but I have been unable to pinpoint another point of failure.

The local site is running at some-local-domain.org:3000 with the /etc/hosts file:

127.0.0.1 localhost
127.0.0.1 some-local-domain.org

Google OAuth web app configuration is as follow.

Authorized origins:

http://some-local-domain.org
http://some-local-domain.org:3000
http://localhost
http://localhost:3000

Authorized redirect uris:

http://some-local-domain.org/login
http://some-local-domain.org:3000/login
http://localhost/login
http://localhost:3000/login

And for completeness the prompt to sign in with Google is being triggered as follows:

widow.google.accounts.id.initialize({
  client_id: clientId,
  callback: onLoginSuccess,
  context: 'signin',
});
...
window.google.accounts.id.prompt(onPromptNotification);

The error: The given origin is not allowed for the given client ID.

With the above origins I also tested clearing the cache and creating a new credential without success. Tips welcome!


Solution

  • So Google only supports localhost and localhost ip addresses (ex. 127.0.0.1) on HTTP. As soon as you start using custom domains/subdomains you need to be using HTTPS.

    Ref docs ( https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#origin-validation):

    JavaScript origins must use the HTTPS scheme, not plain HTTP. Localhost URIs (including localhost IP address URIs) are exempt from this rule.

    Attempted to do this via ngrok without success, however caddy + mkcert worked with some setup. Probably best to check the actual docs but below is an outline of simple setup.

    Setup mkcert:

    brew install mkcert
    mkcert -install
    mkdir -p certs
    mkcert -cert-file certs/some-local-domain-cert.pem \
      -key-file certs/some-local-domain-key.pem *.some-local-domain.com
    

    Setup caddy:

    brew install caddy
    

    Write a config file:

    some-local-domain.com {
        reverse_proxy localhost:3000
        tls certs/some-local-domain-cert.pem certs/some-local-domain-key.pem
    }
    

    and update your /etc/hosts to include the proxy domain.

    Start/stop caddy:

    sudo caddy start --config ./Caddyfile
    sudo caddy stop --config ./Caddyfile
    

    Now add your https://some-local-domain.com to your authorized origins and visit https://some-local-domain.com to try Google sign in.

    Note: if using node you might also need to set:

    export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"