如何使用 OAuth 访问令牌授权对 Google 日历的请求?

问题描述 投票:0回答:2

我阅读了 OAuth,所以我了解基本原理。我似乎无法得到的是,如果我有访问令牌和日历 ID,如何授权对 Google Calendar API(我使用的是 v3)的请求。
我开发的应用程序应该将数据写入我们的数据库和 Google 日历。因此,当用户授权我的应用程序访问他的日历时,我会收到一个访问令牌和一个日历 ID。我的问题是我下一步该怎么做?
我读了大约十几篇关于这个主题的文章,其中只有一篇有使用 ASP.NET MVC 4 的完整示例 - 但问题是它使用了 Google 未列出的过时的 NuGet 包。尝试移植它,但类名、方法名和参数列出了所有更改,所以现在我不知道该怎么办。
附注当然,我看到了有关在 ASP.NET MVC 中使用 OAuth 的 Google 文档,但这对我没有多大帮助,因为我不知道将访问令牌放在哪里。

.net oauth google-calendar-api
2个回答
2
投票

如果您使用不记名令牌,您的代码应类似于:

var webClient = new WebClient();
webClient.Headers.Add("Authorization", "Bearer " + AccessToken);
result = webClient.UploadString(Url, "POST", PostData);

原始请求看起来像这样(忽略 POST/GET 差异):

GET /calendar/v3/users/me/calendarList/{calendarId} HTTP/1.1
Host: www.googleapis.com
Content-length: 0
Authorization: Bearer <bearer-token>

我建议使用 Google OAuth 2.0 Playground 进行测试以熟悉 API。


0
投票

以防万一有人使用新的身份验证方法和最新的谷歌代码寻找这个答案

<html lang="en">
<head>
    <title>Agents Portal</title>
    <script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
    <script>
      const GOOGLE_CLIENT_ID = "XXXXXXXX.apps.googleusercontent.com"
    </script>
</head>
<body>
<div style="text-align: center;">
    <div style="font-size: 24px;"> Auth with google</div>
    <button style="font-size: 24px;" onclick="getAuthCode();">Load Your Calendar</button>
    <div style="margin-top: 50px; font-size: 20px" id="code"></div>
    <script>
      let client;

      function initClient() {
        client = google.accounts.oauth2.initCodeClient({
          client_id: GOOGLE_CLIENT_ID,
          scope: 'https://www.googleapis.com/auth/calendar',
          ux_mode: 'popup',
          callback: async (response) => {
            console.log(response)
            document.getElementById('code').innerText = response.code
          },
        });
      }

      function getAuthCode() {
        // Request authorization code and obtain user consent
        client.requestCode();
      }
    </script>
</div>
</body>
</html>

获取代码后,将其保存到数据库并使用该“信任”代码来使用日历 API(或其他范围)。

© www.soinside.com 2019 - 2024. All rights reserved.