Google Sign In


我們平常也經常使用QQ,微信賬號,登錄其他應用。最近公司讓我給網站添加一個谷歌賬號登錄。我來這里記錄一下,莫怪~~~莫怪~~~

1. 申請一個賬號登錄ID:  https://developers.google.com/identity/sign-in/web/sign-in#before_you_begin

2. 拿到ID:  

var clientId = "**********.apps.googleusercontent.com";

3. 在官網https://developers.google.com/identity/sign-in/web/有一段代碼更改下clientId就可以在頁面中使用,只是效果可能與實際需求有點差別。

<html lang="en">
<head>
    <title>test.html</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="*** Your client_id ***.apps.googleusercontent.com" />
    <script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script type="text/javascript">
        function onSignIn(googleUser) {
            var profile = googleUser.getBasicProfile();
            var parameter = {
                id: profile.getId(),
                userName: profile.getName(),
                email: profile.getEmail(),
                imageUrl: profile.getImageUrl(),
                givenName: profile.getGivenName(),
                familyName: profile.getFamilyName(),
                imgUrl: profile.getImageUrl()
            };
var vid_token = googleUser.getAuthResponse().id_token; } function signOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); }</script> </head> <body> <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> <a href="#" onclick="signOut();">Sign out</a> </body> </html>

4. 來啦來啦,下面是我根據公司網站和實際需求,參考着官網上寫的代碼。(感覺公司對待某些網站功能時,挺隨意的,需要的說添加就添加。呃,我啥也沒說~_~~~)

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
    <style type="text/css">
        .g-signin-wrapper {
            padding: 5px 0;
        }

        .customGPlusSignIn {
            display: inline-block;
            width: 180px;
            /* 背景顏色設定 */
            background-color: #4285f4;
            color: #ffffff;
            border-radius: 5px;
            border: thin solid #888;
            box-shadow: 1px 1px 1px grey;
            white-space: nowrap;
        }
        .customGPlusSignIn:hover {
            cursor: pointer;
        }
        .label {
            /* display: none; */
            padding-left: 3px;
            color: #676767;
            font-family: serif;
            font-weight: normal;
        }
        .icon {
            display: inline-block;
            vertical-align: middle;
            width: 34px;
            height: 24px;
            background: url('https://developers.google.com/identity/sign-in/g-normal.png') transparent 3px 50% no-repeat;
            background-color: #ffffff;
            border-radius: 5px 0 0 5px;
        }
        .buttonText {
            display: inline-block;
            vertical-align: middle;
            width: 140px;
            font-size: 14px;
            font-weight: bold;
            font-family: 'Roboto', sans-serif;
            text-align: center;
        }
    </style>
    <script>
        var clientId = "******.apps.googleusercontent.com";
        //登錄按鈕事件
        function GoogleLogin() {
            gapi.load('auth2', function () {
                var auth2 = gapi.auth2.init({
                    client_id: clientId,
                    //fetch_basic_profile: false, //這里true或false的值會影響,下面的googleUser.getBasicProfile()的取值和api驗證返回結果res的值
                    fetch_basic_profile: true,
                    scope: "profile email"
                });

                auth2.signIn().then(function (googleUser) {
                    var profile = googleUser.getBasicProfile();
                    var response = googleUser.getAuthResponse();

                    var parameter = {
                        id: profile.getId(),
                        userName: profile.getName(),
                        email: profile.getEmail(),
                        imageUrl: profile.getImageUrl(),
                        givenName: profile.getGivenName(),
                        familyName: profile.getFamilyName()
                    };

                    var verifyUrl = "https://oauth2.googleapis.com/tokeninfo?id_token=" + response.id_token;
                    getRespone(verifyUrl);
                });
            });
        }

        function getRespone(url) {
            $.ajax({
                type: "GET",
                cache: false,
                url: url,
                success: function (res) {
                    console.log(res);   // res: api驗證后的結果
                }
            });
        }
    </script>
</head>
<body>
    <div id="gSignInWrapper" class="g-signin-wrapper">
        <span class="label">Sign in with:</span>
        <div id="customBtn" class="customGPlusSignIn" onclick="GoogleLogin()">
            <span class="icon"></span>
            <span class="buttonText">Sign in with Google</span>
        </div>
    </div>
</body>
</html>

5.API: https://oauth2.googleapis.com/tokeninfo?id_token=*********驗證通過的返回值

{
   alg: "RS256"
  at_hash: "EZlzneWBRJGP4318W12vZQ"
  aud: "******.apps.googleusercontent.com"  /* 與ClientID的值相同 */
  azp: "******.apps.googleusercontent.com"
  email: "******@gmail.com"    /* google的郵箱賬號 */
  email_verified: "true"  /* 是否是郵箱賬號 */
  exp: "1565577892"
  family_name: "AA"  /* 姓 */
  given_name: "vvv"  /* 名 */
  iat: "1565574292"
  iss: "accounts.google.com"  /* google賬號登錄的標識 */
  jti: "ce11dc29ac53aa52533f5489b1dde03988035785"
  kid: "60f4060e58d75fd3f70beff88c794a775327aa31"
  locale: "zh-CN"
  name: "vvv AA"  /* 姓名 */
  picture: "https://lh6.googleusercontent.com/**********/photo.jpg"  /* 頭像url */
  sub: "116604411058332859522"    /* 與上面的googleUser.getBasicProfile().getId()相同 */
  typ: "JWT"
}

6. 在瀏覽器加載頁面時,判斷是否登錄google賬號,若已登錄,則彈出提示窗口。

 這個功能在iframe嵌套的頁面會出錯,具體原因不知道,聽老大說,有些服務會禁止在iframe嵌套的頁面使用。

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://smartlock.google.com/client" defer></script>
    <script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
    <script>
        var clientId = "******.apps.googleusercontent.com";

        //進入頁面,Google登錄彈窗提示
        window.onGoogleYoloLoad = function (googleyolo) {
            var config = {
                supportedAuthMethods: ["https://accounts.google.com"],
                supportedIdTokenProviders: [{ uri: "https://accounts.google.com", clientId: clientId }]
            };

            googleyolo.hint(config).then(function (credential) {
                getRespone("https://oauth2.googleapis.com/tokeninfo?id_token=" + credential.idToken);
            }, function (error) {
                console.log(error);
            });
            
            var bodyObserver = new MutationObserver(function (mutationsList) {
                for (var i = 0; i < mutationsList.length; i++) {
                    var mutation = mutationsList[i];

                    for (var j = 0; j < mutation.addedNodes.length; j++) {
                        var node = mutation.addedNodes[j];
                        if (node.nodeName === 'IFRAME' && node.src.includes('smartlock.google.com/iframe/')) {
                            bodyObserver.disconnect();
                            node.onmouseover = function () {
                                clearInterval(timer);
                            }
                            node.onmouseleave = function () {
                                timer = setTimeout(function () { node.style.display = "none"; }, 5000);
                            }
                 // 10秒后隱藏窗體
var timer = setTimeout(function () { node.style.display = "none"; }, 10000); } } } }); bodyObserver.observe(window.document.body, { childList: true }); } function getRespone(url) { $.ajax({ type: "GET", cache: false, url: url, success: function (res) { console.log(res); // res: api驗證后的結果 } }); } </script> </head> <body> <!-- 參考鏈接:
    https://github.com/zapier/google-yolo-inline/blob/master/google-yolo-iframe.html
    https://github.com/openid/OpenYOLO-Web
    https://medium.com/groww-engineering/all-about-googles-one-tap-sign-in-b8c1c93305d4
   --> </body> </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM