Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google token string depreciated please use auth code object #5078

Closed
Haseebshah936 opened this issue Nov 5, 2022 · 21 comments
Closed

Google token string depreciated please use auth code object #5078

Haseebshah936 opened this issue Nov 5, 2022 · 21 comments

Comments

@Haseebshah936
Copy link

Haseebshah936 commented Nov 5, 2022

How frequently does the bug occur?

All the time

Description

Uncaught (in promise) Error: google(<tokenString>) has been deprecated. Please use google(<authCodeObject>).
I have received this error. All tough I was following the original docs both for google one tap connect and realm. Did some digging and found that this error shows when creating realm credential for google. I am using the realm web sdk with react. This error is generating from {{bundle.dom.es.js }}at line 2386 in method derivePayload. If there is any solution or some has faced this issue before it will be grate if you can share the solution. The same issue can be recreated by using the code provided in the realm web sdk google authentication code sample.

https://www.mongodb.com/docs/realm/web/authenticate/#std-label-web-google-onetap

Stacktrace & log output

No response

Can you reproduce the bug?

Yes, always

Reproduction Steps

No response

Version

2.0.0

What SDK flavour are you using?

Atlas App Services (auth, functions, etc.)

Are you using encryption?

No, not using encryption

Platform OS and version(s)

Mac

Build environment

React

Cocoapods version

No response

@kneth
Copy link
Member

kneth commented Nov 7, 2022

@Haseebshah936

In order to make the API clear, we have moved from positional parameters to named parameters. From version 2.0.0 you should use

const autoCode = ...;
const creds = Realm.Credentials.google({
  authCode
});

@sync-by-unito sync-by-unito bot added the Waiting-For-Reporter Waiting for more information from the reporter before we can proceed label Nov 7, 2022
@Haseebshah936
Copy link
Author

Haseebshah936 commented Nov 8, 2022

const googleAuth = React.useCallback(
    async (code) => {
      const credentials = Realm.Credentials.google(code);
      console.log(credentials);
      try {
        // Authenticate the user
        const user = await realmApp.logIn(credentials);
        // `App.currentUser` updates to match the logged in user
        console.assert(user.id === realmApp.currentUser.id);
        return user;
      } catch (err) {
        console.error("Failed to log in", err);
      }
    },
    [realmApp]
  );

// Google One Tap Login
const loadScript = (src) =>
    new Promise((resolve, reject) => {
      if (document.querySelector(`script[src="${src}"]`)) return resolve();
      const script = document.createElement("script");
      script.src = src;
      script.onload = () => resolve();
      script.onerror = (err) => reject(err);
      document.body.appendChild(script);
    });

  const googleButton = useRef(null);

// loading script for google oneTap and rendering google button

  useEffect(() => {
    const src = "https://accounts.google.com/gsi/client";
    const id =
      "Client Id ;)";

    loadScript(src)
      .then(() => {
        /*global google*/
        console.log(google);
        google.accounts.id.initialize({
          client_id: id,
          callback: handleCredentialResponse,
        });
        google.accounts.id.renderButton(googleButton.current, {
          theme: "filled_blue",
          size: "large",
        });
      })
      .catch(console.error);

    return () => {
      const scriptTag = document.querySelector(`script[src="${src}"]`);
      if (scriptTag) document.body.removeChild(scriptTag);
    };
  }, []);

// Call back function triggered when google button is pressed

  async function handleCredentialResponse(response) {
    console.log("Encoded JWT ID token: " + response.credential);
    googleAuth(response.credential);
  }

Here is my code which gave the error. I think I am already using this method. The code here was coming from google one tap login. I have also tested it against @react-oauth/google.

// @react-oauth/google.

const googleAuth = useGoogleLogin({
    flow: "auth-code",
    onSuccess: async ({ code }) => {
      console.log(code);
      const credentials = Realm.Credentials.google(code);
      realmApp
        .logIn(credentials)
        .then((user) => alert(`Logged in with id: ${user.id}`));
    },
    redirect_uri: "http://localhost:3000/home",
  });

@github-actions github-actions bot added Needs-Attention Reporter has responded. Review comment. and removed Waiting-For-Reporter Waiting for more information from the reporter before we can proceed labels Nov 8, 2022
@kneth
Copy link
Member

kneth commented Nov 17, 2022

Please try to change const credentials = Realm.Credentials.google(code) to const credentials = Realm.Credentials.google({ authCode: code })

@sync-by-unito sync-by-unito bot added Waiting-For-Reporter Waiting for more information from the reporter before we can proceed and removed Needs-Attention Reporter has responded. Review comment. labels Nov 18, 2022
@takameyer
Copy link
Contributor

@Haseebshah936 Did the suggested change help?

@Haseebshah936
Copy link
Author

Sorry for the delay in reply but no the suggested solution doesn't worked it returened realm auth. Quite frankly I didn't remember the exact response. But I will share it in a while.

@github-actions github-actions bot added Needs-Attention Reporter has responded. Review comment. and removed Waiting-For-Reporter Waiting for more information from the reporter before we can proceed labels Jan 3, 2023
@takameyer
Copy link
Contributor

@Haseebshah936 If this doesn't work:

const credentials = Realm.Credentials.google({ authCode: code })

try this:

const credentials = Realm.Credentials.google({ idToken: code })

@sync-by-unito sync-by-unito bot added Waiting-For-Reporter Waiting for more information from the reporter before we can proceed and removed Needs-Attention Reporter has responded. Review comment. labels Jan 4, 2023
@jwing8
Copy link

jwing8 commented Jan 5, 2023

I'm running into the same issue. I tried changing the parameter from a string (which worked prior to 2.0) to an object, testing both authCode and idToken as properties, however I keep getting the following error: TypeError: (intermediate value).google is not a function

The documentation stills refers to passing in a string in the example provided on https://www.mongodb.com/docs/realm/web/authenticate/#std-label-web-login-google

@Haseebshah936
Copy link
Author

Sorry for the delay in reply.
I have received this error after trying idToken
error fetching info from OAuth2 provider (status 401) at MongoDBRealmError.fromRequestAndResponse
and this when using authCode:
error exchanging access code with OAuth2 provider (status 401) at MongoDBRealmError.fromRequestAndResponse

@github-actions github-actions bot added Needs-Attention Reporter has responded. Review comment. and removed Waiting-For-Reporter Waiting for more information from the reporter before we can proceed labels Jan 7, 2023
@takameyer
Copy link
Contributor

Ok, we will investigate this further. I'll update here when we have something to report.

@sync-by-unito sync-by-unito bot removed the Needs-Attention Reporter has responded. Review comment. label Jan 9, 2023
@Haseebshah936
Copy link
Author

ok

@jwing8
Copy link

jwing8 commented Jan 13, 2023

I think the issue may have been introduced in 1.6.0 or later because I was able to get this working in 1.5.1 but none of the later versions.

@takameyer
Copy link
Contributor

@Haseebshah936 The changes made to 2.0.0 are visible here:
8472cb0#diff-ece863e03f42ffef7e48ed9ec9afb7386df3abf7022aea3c1552c7837fda6b75
Basically we are letting you decide from the application code which authentication string you want to set. In your case, idToken should be the correct one.

That being said, I don't see anything in our code that would cause you to start receiving authentication errors. Perhaps there is an issue with the configuration. Can you verify that everything is setup correctly in App Services?

@jwing8 Your error looks quite different than what is reported here. Can you make a separate issue and show some example code, as well as what versions of realm-web you are using.

@takameyer
Copy link
Contributor

We wrote a small test application that you can use as an example to authorize:
https://codesandbox.io/s/realm-web-google-auth-vanilla-ujkc0o

You can replace the app-id with yours. If everything is properly configured, both in Atlas and in Google, it should work.

@Haseebshah936
Copy link
Author

@takameyer Here are the App services setting
image
More over on trying the sandbox version you provided the google button disappears when i replaced the realm id in index.html with my app id. I tried adding the url to the app setting as allowed but it throughs error that the origin not allowed any idea about that would also be help full.

@takameyer
Copy link
Contributor

takameyer commented Jan 16, 2023

@Haseebshah936 You will have to configure the request origins, both in atlas and in google dashboard, for the sandbox application (https://ujkc0o.csb.app/). In any case, carefully review our Atlas documentation and google's documentation on how to setup google authentication.
Specifically this section should be correctly set in order to avoid 401 errors.

@Srujan1527
Copy link

@takameyer @kneth @Haseebshah936 @timanglade
can u explain how to get the auth code with a sample example

@matt2legit
Copy link

I've tried the idToken and authCode on web and no matter what I'm getting a 401 error. What makes this even more bizarre is that it works just fine with the authCode in React Native. The code's look similar on both, so I don't understand why it's not working on web.

@matt2legit
Copy link

I finally got it to work by turning on OpenID Connect and using the idToken.

I still don't understand why the authCode doesn't work on web or why metadata doesn't save when it's available in the idToken. As a work around, I used jwt_decode to extract it from the idToken and saved it to customData as suggested on another issues.

FWIW, I think most of the issues/improvements are needed server side and not with the realm-js library. Where is the best place to provide that feedback?

@Srujan1527
Copy link

`You can pass redirectUri like below instead of authCode(If you don't have)

    const redirectUri = "http://localhost:3000";

    const credentials = Realm.Credentials.google({
      redirectUrl: redirectUri,
    });
    console.log(credentials);
 

    app
      .logIn(credentials)
      .then((user) => alert(`Logged in with id:${user.id}`))
      .catch((err) => console.log(err));`

@jwing8
Copy link

jwing8 commented Mar 23, 2023

We wrote a small test application that you can use as an example to authorize: https://codesandbox.io/s/realm-web-google-auth-vanilla-ujkc0o

You can replace the app-id with yours. If everything is properly configured, both in Atlas and in Google, it should work.

This example helped me resolve my issue. Apparently I wasn't destructuring the idToken properly, so user error on my part (no additional config or passing in of redirectUrl needed). Thank you very much for providing the sandbox example.

@takameyer
Copy link
Contributor

Closing since this is not an issue we can fix. Google auth is not straightforward to implement and its easy to mess up. If you are having issues, please consult our forums or talk to your MongoDB representative.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 14, 2024
@sync-by-unito sync-by-unito bot changed the title Google token string depreciated please use auth code object Google token string depreciated please use auth code object Mar 14, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

7 participants