Google OAuth via gapi.signin2.render button not hitting callbacks in react app

佐手、 提交于 2020-01-05 07:37:04

问题


I have the Google Signin Button properly rendering inside my react component using the gapi.signin2.render method on the latest Google platform web-client api (https://apis.google.com/js/platform.js).

But, for the life of me, I can't get it to properly call my success or failure callbacks.

The button renders, clicking the button opens the account auth window, clicking a Google account closes the window, but no callback.

function myCallback(obj) {
  console.log(obj);
}

gapi.signin2.render('my-signin2', {
  scope: 'https://www.googleapis.com/auth/plus.login',
  width: 200,
  height: 50,
  longtitle: true,
  theme: 'dark',
  onsuccess: myCallback,
  onfailure: myCallback
});

I have no clue what I'm missing here. Any help is much appreciated!


回答1:


When you created your client ID you set your url to , let us say 'localhost'. Now you running you code on, let us say 'localhost:8080'. your 'myCallback' is not running because there is no data coming back from google api, the data is sent to the trusted url that you specified which is 'localhost'. The idea is simple, the request can come from anywhere, but google api is sending the data to your trusted url as a security step, if the request is coming from there you get it, if it is not someone is trying to hack using your client ID.




回答2:


The docs tell you to add this:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

But that won't work with React. I found that removing data-onsuccess and class (className) from the div did the trick. So if you have something like this:

  useEffect(() => {
    window.gapi.signin2.render('gs2', {
      'scope': 'https://www.googleapis.com/auth/plus.login',
      'width': 200,
      'height': 50,
      'longtitle': true,
      'theme': 'dark',
      'onsuccess': onGoogleSignIn
    });
  }, []);

  const onGoogleSignIn = user => {
    console.log('user', user);
  }

then your jsx for the google button can simply be this:

<div id="gs2"></div>

note that I removed the class and added id because gapi.signin2.render is looking for an id.

The caveat is that now you lose the styling. Unfortunately, addingclassName="g-signin2" back to the div actually breaks the callbacks.



来源:https://stackoverflow.com/questions/40480080/google-oauth-via-gapi-signin2-render-button-not-hitting-callbacks-in-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!