如何发起OAuth2.0流程?

How to initiate OAuth2.0 flow?

如何POST到Google的OAuth 2.0端点进行授权?

我正在用 React 构建一个 chrome 扩展,并且一直在关注 Google's documentation。看起来很简单,但我没有完全掌握实现的机制。

例如,在我的 popup.js 文件中,我调用了我的 background.js 文件,该文件对创建的重定向 url 执行 axios POST 请求。指南中的第 3 步说 Google 将提示用户同意,但是,这从未发生过。我收到 200 条回复,但不确定之后该去哪里。

我做错了什么?谢谢!

  axios
      .post(
        `https://accounts.google.com/o/oauth2/v2/auth?
         scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
         include_granted_scopes=true&
         response_type=token&
         state=state_parameter_passthrough_value&
         redirect_uri=https%3A//oauth2.example.com/code& 
         client_id=client_id` //actual values added
      )
      .then(function (response) {
        console.log('RESPONSE', response);
      });

该文档中的第 2 步标题为

Step 2: Redirect to Google's OAuth 2.0 server

您正在尝试使用 POST 进行 XHR 请求。

该文档提供了带有和不带有客户端库的示例代码。没有客户端库,你可以看到它是一个使用表单的GET请求(它改变了浏览器中的URL,有效地重定向):

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

  // Create <form> element to submit parameters to OAuth 2.0 endpoint.
  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',
                'response_type': 'token',
                'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
                'include_granted_scopes': 'true',
                'state': 'pass-through value'};

  // 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();
}