如何利用google账号登录第三方平台实现

2,491 阅读1分钟

1. 开通google账号

进入开发者后台:[console.cloud.google.com/welcome]

2. 进入API与服务

image.png

3. 进入凭证-创建凭证

image.png

根据需求选择合适的凭据类型

我们选择OAuth客户端ID类型为例, Google的OAuth服务器使用客户端ID去标识单个应用。 image.png

我们选择Web应用

image.png 其中,添加的 已获授权的 JavaScript 来源 表示"托管您的 Web 应用的 HTTP 来源",如果是本地调试的话,通常设置为http://localhost

已获授权的重定向 URI,比如设置了http://localhost:5173, 表示google OAuth服务器 授权成功后跳转的地址, ,如下形式

http://localhost:5173/#state=try_sample_request&access_token=ya29.a0AbVbY6PHgehZoZbp5RPDmj27McxNzCmMkppiscR2cT5NX3uT3oVF10k15KSIG_KiBrOo7RnP_Qm08TtUAknY_c1rQsXPnjJulVn2ANUZXWQkj-806cw95TLzT1AFPdfHlVoN4A7gJNinY2dbfWYfPLMf8NpnaCgYKAYwSARMSFQFWKvPl96rwxRCwdTK_dtJcD_QKIA0163&token_type=Bearer&expires_in=3599&scope=https://www.googleapis.com/auth/drive.metadata.readonly

返回了access_token, token_type, scope, 等

OAuth 同意屏幕

image.png

相关代码如下:

<html>
<head>
</head>
<body>
<script>
  var YOUR_CLIENT_ID = 'REPLACE_THIS_VALUE';
  var YOUR_REDIRECT_URI = 'REPLACE_THIS_VALUE';
  var fragmentString = location.hash.substring(1);

  // Parse query string to see if page request is coming from OAuth 2.0 server.
  var params = {};
  var regex = /([^&=]+)=([^&]*)/g, m;
  while (m = regex.exec(fragmentString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }
  if (Object.keys(params).length > 0) {
    localStorage.setItem('oauth2-test-params', JSON.stringify(params) );
    if (params['state'] && params['state'] == 'try_sample_request') {
      trySampleRequest();
    }
  }

  // If there's an access token, try an API request.
  // Otherwise, start OAuth 2.0 flow.
  function trySampleRequest() {
    var params = JSON.parse(localStorage.getItem('oauth2-test-params'));
    if (params && params['access_token']) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET',
          'https://www.googleapis.com/drive/v3/about?fields=user&' +
          'access_token=' + params['access_token']);
      xhr.onreadystatechange = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
          console.log(xhr.response);
        } else if (xhr.readyState === 4 && xhr.status === 401) {
          // Token invalid, so prompt for user permission.
          oauth2SignIn();
        }
      };
      xhr.send(null);
    } else {
      oauth2SignIn();
    }
  }

  /*
   * Create form to request access token from Google's OAuth 2.0 server.
   */
  function oauth2SignIn() {
    // Google's OAuth 2.0 endpoint for requesting an access token
    var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

    // Create element to open OAuth 2.0 endpoint in new window.
    var form = document.createElement('form');
    form.setAttribute('method', 'GET'); // Send as a GET request.
    form.setAttribute('action', oauth2Endpoint);

    // Parameters to pass to OAuth 2.0 endpoint.
    var params = {'client_id': YOUR_CLIENT_ID,
                  'redirect_uri': YOUR_REDIRECT_URI,
                  'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                  'state': 'try_sample_request',
                  'include_granted_scopes': 'true',
                  'response_type': 'token'};

    // Add form parameters as hidden input values.
    for (var p in params) {
      var input = document.createElement('input');
      input.setAttribute('type', 'hidden');
      input.setAttribute('name', p);
      input.setAttribute('value', params[p]);
      form.appendChild(input);
    }

    // Add form to page and submit it to open the OAuth 2.0 endpoint.
    document.body.appendChild(form);
    form.submit();
  }
</script>

<button onclick="trySampleRequest();">Try sample request</button>
</body>
</html>

相关文档参考:

developers.google.com/identity/pr…