如何使用 Google Oauth2.0 通过 Telegram Bot 验证用户

How to use Google Oauth2.0 to authenticate user via Telegram Bot

这是我第一次与 Google API 互动,我正在使用 python3.9 和这个库 Python Telegram Bot 我想通过电报机器人访问用户 Google API 日历,但我似乎找不到任何文章来指导我完成它。我的关键问题(我认为)是将成功授权流程重定向回电报机器人。

这是我的想法:

  1. 在电报应用中,用户发送“/send”给机器人
  2. Bot 接收消息和 return google 授权 link 给用户
  3. 用户 clink 授权 link 并允许访问
  4. Bot 接收授权访问并完成 Oauth 流程

问题出在第 3 步和第 4 步之间。标准授权 link 是 https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=<clientid>&redirect_uri=<redirect_uri>&scope=<scope>&state<state>&access_type=offline

如何将授权 link 发送回我的电报机器人?我是否应该创建另一个 API 端点来接收该授权 link?或者我可以在 中发送电报 api send_message() 以将成功消息重定向到我的机器人。

更新 1

感谢 CallMeStag,我设法找到了一种方法来完成 oauth 过程。对于遇到同样问题的人,这就是我所做的 先决条件:凭据是在 google 控制台 api - Web 应用程序中创建的。 redirect_uri 设置为 localhost:8000(在开发阶段)

  1. 用户向 bot 发送“/send”
  2. 机器人收到消息和return授权link
    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=<clientid>&redirect_uri=http://localhost:8000/&scope=<scope>&state<state>&access_type=offline
    
  3. 用户点击 link 进行身份验证,它将重定向到 http://localhost:8000。使用 fastapi 作为 webhook 来接收消息。获取授权码,使用google.oauthlib.flow完成授权过程。接下来,将用户重定向回电报 link https://t.me/<botname>
  4. 开始使用用户 google 日历

目前 PTB-application 监听外部更新(本例中的 auth 验证)确实不是很直接 - 另请参见 this issue. Currently it might be easiest for you to set up a custom webhook application that runs in parallel to the Updater - e.g. using flask/django/starlette/fastapi/…. Alternatively, if you're using webhooks for your bot anyway, you can patch the Updater to do the job for you. Although that requires some manual work - see here 示例。

一旦您能够侦听来自 Google 的更新,就可以通过 PTB 通常的处理程序设置来处理它们,特别是通过 TypeHandler 甚至自定义 Handler 子类- 看这个 FAQ entry.

关于重定向 url:您需要将用户重定向回您的机器人,因此您必须提供一个 link 来执行此操作。 Bot.link 应该可以解决问题。


免责声明:我目前是 python-telegram-bot.

的维护者