Google Sign In with redirect

不打扰是莪最后的温柔 提交于 2021-02-07 10:36:31

问题


I'm trying to implement a simple google sign in, and since the popup is often blocked by the browser, I've set ux_mode: "redirect"

This is what I did:

//Inside https://example.com/login/index.php
onload = function() {
    gapi.load("auth2", function() {
        var auth = gapi.auth2.init({
            client_id: "{MY_CLIENT_ID}.googleusercontent.com",
            fetch_basic_profile: false,
            scope: "email",
            cookie_policy: "none",
            ux_mode: "redirect",
            redirect_uri: "https://example.com/login/auth.php"
        });

        auth.attachClickHandler(google.querySelector("span"));
    });
}

I don't need to store my token inside the database: what I need is simply retrieving the user's email to log him in without the need of a password.

This is the fragment that I get after the authentication: #scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email&id_token={TOKEN}&login_hint={HINT}&client_id={MY_CLIENT_ID}.googleusercontent.com

Since onsuccess and onfail do not work with the redirect (see here and here), I need a way to get users' email directly from https://example.com/login/auth.php (the page I redirect to).

If I initialize another auth:

   gapi.load("auth2", function(){
        var auth = gapi.auth2.init({
            client_id: "{MY_CLIENT_ID}.apps.googleusercontent.com",
            fetch_basic_profile: false,
            scope: "email",
        });

the fragment returned by google disappears and I get a new empty GoogleAuth object, so I have to guess that this is not the way to go.

I also tried with gapi.auth2.getAuthInstance().currentUser.get() but it returns undefined.

Same behavior if I redirect on the same page (I prefer redirecting somewhere else since I have to redirect again after I retrieve the email, and redirecting on the same page would load index.php again in vain).

I have whitelisted both https://example.com/login/index.php and https://example.com/login/auth.php (even if only the former is required).

So, what do I need?

  • Get the user's email from auth.php using GoogleUser.getBasicProfile()
  • If this is not possible, exchange the token and the information that I find inside the fragment for the user's email from the frontend/backend

Obviously the first solution would be better since I shouldn't redirect somewhere else again with a cURL request (really slow) or something like that.


I know that questions like this regarding the APIs are often ignored (half of them are answer-less on Stack Overflow). Any response would be appreciated, because I feel that I'm missing something really simple that could seem obvious.

来源:https://stackoverflow.com/questions/61924325/google-sign-in-with-redirect

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