Realm-web Google Auth error exchanging access code with OAuth2 provider

Hi, I’m trying to implement Google Auth using realm-web but I’m getting error during exchanging authCode for accessToken with stitch service
app.logIn(Realm.Credentials.google(authCode));

stitch respond with

{error: "error exchanging access code with OAuth2 provider", error_code: "AuthError",…}

My Google OAuth2 Client

Client ID for Web application
Authorized JavaScript origins
URI: [https://realm.mongodb.com]
Authorized redirect URIs: [
https://realm.mongodb.com/api/client/v2.0/auth/callback, 
https://realm.mongodb.com/api/client/v2.0/auth/callback, 
https://us-west-2.aws.realm.mongodb.com/api/client/v2.0/auth/callback, 
https://eu-west-1.aws.realm.mongodb.com/api/client/v2.0/auth/callback, 
https://ap-southeast-2.aws.realm.mongodb.com/api/client/v2.0/auth/callback, 
https://stitch.mongodb.com/api/client/v2.0/auth/callback]

my oauth2-google.json

{
    "id": "5fc81536e620d067d2edcfac",
    "name": "oauth2-google",
    "type": "oauth2-google",
    "config": {
        "clientId": "10571797xxxx-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
    },
    "secret_config": {
        "clientSecret": "google_ouath_client_secret"
    },
    "disabled": false
}

client app

          <GoogleLogin
            clientId="10571797xxxx-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
            buttonText="Login"
            responseType="code"
            onSuccess={(response) => {
              if (response.code) {
                loginWithGoogle(response.code);
              }
            }}
            onFailure={(response) => {/*omited*/}}
          />

  const loginWithGoogle = async (authCode: string) => {
    try {
      await app.logIn(Realm.Credentials.google(authCode));
    } catch (e) {
      console.error(e)
    }
  };

Yes, I’m using responseType="code", and I successfully receive authCode from Google.
But, HTTP call of app.login looks like this

Request URL: https://stitch.mongodb.com/api/client/v2.0/app/xxxxxxx-app-pozwq/auth/providers/oauth2-google/login
Request Method: POST
Status Code: 401 
Remote Address: 52.16.113.157:443
Referrer Policy: strict-origin-when-cross-origin

{"authCode":"4/0AY0e-g6OJPnXe4KLQYWOYSkm2b6aWxxxxxxxxxxxxxxxxxxxxxxxx","options":{"device":{"sdkVersion":"1.0.0","platform":"chrome","platformVersion":"86.0.4240","deviceId":{"$oid":"5fc802b2723axxxxx"}}}}

Response

{"error":"error exchanging access code with OAuth2 provider","error_code":"AuthError","link":"https://realm.mongodb.com/groups/5f71b53f1bbd91xxxxxxxxxxxxxxxxxxxxxxxxx"}

What am I doing wrong ?

Hi @Stanislaw_Baranski,

The Google auth api has changed and now you need to get the Auth code from the google sdk and not from our endpoint
https://docs.mongodb.com/realm/web/authenticate#google-oauth

The redirect will work but only for the first 100 google users then it will block. Its for development purpose only and is not recommended way.

Thanks
Pavel

@Pavel_Duchovny, I know, and this is exactly what I’m doing, and it doesn’t work, that’s why I’m writing here.

I’m the only one facing this problem? I’m trying to solve it for a week now. I checked everything. @Pavel_Duchovny have I done something wrong ? I’m getting the auth code from google sdk, not from your endpoint. I’m sending you the authCode and not a token.

"authCode":"4/0AY0e-g6OJPnXe4KLQYWOYSkm2b6aWxxxxxxxxxxxxxxxxxxxxxxxx"

@Stanislaw_Baranski I ran into this issue a ton while setting up Google auth in a React Native project and never really found a true solution. I was originally using the library react-native-app-auth and nothing seemed to be working even though I’m pretty certain everything was set up correctly. I then tried using a different library, @react-native-community/google-signin, and everything just started working. I still don’t know why the first library didn’t work with Realm, but I guess my suggestion is to try using a different library to handle the oauth and see if that does anything.

Thank you! Although you didn’t solve my problem, you gave me a clue that the problem may lie on my side.
After digging in, I found a possible cause.
Realm auth uses non-standard gapi.auth2.authorize authentication flow, while the library I use react-google-login uses default gapi.auth2.init/sign-in. I rewrite everything to use standard google sdk, and recommended authorize flow, but it still does not work, I get the same error. Could you please share your configuration? What scopes do you use? Do they match exactly on client side and realm config? Do you enable openId parameter in auth_providers/oauth2-google.json/config/openId (there is no documentation about it, so I assume they added it recently)?

The only configuration I really needed for the flow in React Native was

GoogleSignin.configure({
  webClientId: GOOGLE_WEB_CLIENT_ID,
  iosClientId: GOOGLE_IOS_CLIENT_ID,
  offlineAccess: true,
})

On the Google dev console side, when I download the json for the credentials here’s what I have:

{“web”: {
“client_id”:“xxxxx.apps.googleusercontent.com”,
“project_id”:“xxxxx”,
“auth_uri”:“https://accounts.google.com/o/oauth2/auth”,
“token_uri”:“https://oauth2.googleapis.com/token”,
“auth_provider_x509_cert_url”:“https://www.googleapis.com/oauth2/v1/certs”,
“client_secret”:“xxxxx”,
“redirect_uris”:[
https://realm.mongodb.com/api/client/v2.0/auth/callback”,
https://us-east-1.aws.realm.mongodb.com/api/client/v2.0/auth/callback
],
“javascript_origins”:[“https://realm.mongodb.com”]
}}

For scopes, I have the profile scope and openId.

@Pavel_Duchovny Can you help us to fix this thanks.

I cant use this example:

import * as Realm from "realm-web";
import googleOneTap from 'google-one-tap';
const app = new Realm.App("<Your Realm App ID>");
const client_id = "<Your Google Client ID>";
// Open the Google One Tap menu
googleOneTap({ client_id }, async (response) => {
  // Upon successful Google authentication, log in to Realm with the user's credential
  const credentials = Realm.Credentials.google(response.credential)
  const user = await app.logIn(credentials);
  console.log(`Logged in with id: ${user.id}`);
});

Every time i try i got

Unhandled Rejection (Error): Request failed (POST https://stitch.mongodb.com/api/client/v2.0/app/tasktracker-msbya/auth/providers/oauth2-google/login): error exchanging access code with OAuth2 provider (status 401)
And body posted was:
{"authCode":"eyJhbGciOiJSUzI1....

Thanks for your help.

I believe you need to have OpenID Connect enabled if you want to use Google One Tap. Check your Google provider configuration to see if it’s on - if it’s not try turning it on and see if you still get errors.

Note that OpenID Connect doesn’t include metadata fields, so if your app needs those it won’t fit your use case.

@nlarew Already Turn On :slight_smile:

I didn’t need metadata fields dont worrie ! Just need to have this Google Tab Menu Working :sob:

Can you verify that you’re using Realm Web v1.1.0 or newer?

@kraenhansen Now i am using 1.2.1 ( before 0.8.1 ).

And got new error or code logic, when i login with googleOneTap and use this code:

const credentials = Realm.Credentials.google(response.credential)
const user = await app.logIn(credentials);

realm app create new user just with name data and without email address.

I have checked email address, email verify etc was in JWT token given by googleonetap.

Any idea ? Thanks for your help.

JWT given

@kraenhansen any idea ? :slight_smile:

This seems like a configuration / potential server-side issue, which is slightly out of my domain of expertise. Since this is also a bit off topic, in respects to the original post, my best suggestion is to create a demo app that displays this behavior and create a new post on the forum referencing it, then I’m sure someone will follow up and help you resolve this.

2 Likes