身份认证

这是 Twitter Authentication documentation 的补充。

引言

推特支持 OAuth 1.0a 用户上下文, OAuth 2.0 Bearer Token (App-Only), 也支持具有PKCE (User Context)身份认证方法的 OAuth 2.0 授权代码流。

Twitter API v1.1

OAuth 2.0 Bearer Token (App-Only)

生成 bearer token 最简单的方法是通过Twitter开发者门户下的 Twitter Developer Portal Projects & Apps page.

你能够用 bearer token 初始化 OAuth2BearerHandler ,也能使用 OAuth2BearerHandler 实例初始化 API

import tweepy

auth = tweepy.OAuth2BearerHandler("Bearer Token here")
api = tweepy.API(auth)

或者, 你在Twitter开发者门户下的同一界面找到 API / Consumer key 来初始化 OAuth2AppHandle:

import tweepy

auth = tweepy.OAuth2AppHandler(
    "API / Consumer Key here", "API / Consumer Secret here"
)
api = tweepy.API(auth)

OAuth 1.0a User Context

同样,作为推特开发者账号最简单的认证方法是通过推特开发者门户下的页面直接生成 access token 和 access token secret。 Twitter Developer Portal Projects & Apps page .

你也需要同一页面的 consumer key 和 secret。

你能使用4个凭据初始化 OAuth1UserHandler ,然后使用 OAuth1UserHandler 的实例初始化 API

import tweepy

auth = tweepy.OAuth1UserHandler(
   "API / Consumer Key here", "API / Consumer Secret here",
   "Access Token here", "Access Token Secret here"
)
api = tweepy.API(auth)

要以其他用户进行身份认证, 请看 3-legged OAuth.

Twitter API v2

Tweepy的Twitter API v2方法, Client, 为你处理 OAuth 2.0 Bearer Token (application-only) 和 OAuth 1.0a 用户上下文身份认证。

OAuth 2.0 Bearer Token (App-Only)

生成一个 bearer token 最简单的方法是通过Twitter开发者门户下的 Twitter Developer Portal Projects & Apps page.

你能够这样初始化 Client

import tweepy

client = tweepy.Client("Bearer Token here")

OAuth 1.0a User Context

同样的, 推特开发者账号生成 access token 和 access token secret 最简单的方式是通过`Twitter Developer Portal Projects & Apps page`_.

你也能在上述页面找到 consumer key 和 secret。

你能够通过4个凭证去初始化 Client

import tweepy

client = tweepy.Client(
    consumer_key="API / Consumer Key here",
    consumer_secret="API / Consumer Secret here",
    access_token="Access Token here",
    access_token_secret="Access Token Secret here"
)

要以其他用户进行身份认证, 请看 3-legged OAuth.

OAuth 2.0 Authorization Code Flow with PKCE (User Context)

你能够作为一个用户使用 OAuth2UserHandler 生成 access token 进行身份认证。

你需要在Twitter开发者门户下 Twitter Developer Portal Projects & Apps page 的身份验证设置中,打开OAuth 2.0 , 为此你要提供 Callback / Redirect URI / URL.

然后,您需要注意应用程序的 Client ID, 可以在 Twitter Developer Portal Projects & Apps page 中找到。如果你使用的是 confidential client,则还要生成一个 Client Secret.

之后可以初始化 OAuth2UserHandler

import tweepy

oauth2_user_handler = tweepy.OAuth2UserHandler(
    client_id="Client ID here",
    redirect_uri="Callback / Redirect URI / URL here",
    scope=["Scope here", "Scope here"],
    # Client Secret is only necessary if using a confidential client
    client_secret="Client Secret here"
)

关于作用域的范围,可以看 Twitter’s OAuth 2.0 Authorization Code Flow with PKCE documentation 的作用域部分。

然后可以得到身份认证 URL:

print(oauth2_user_handler.get_authorization_url())

这可用于让用户验证你的应用程序。 一旦他们这样做了,他们将被重定向到您提供的Callback / Redirect URI / URL。 你需要传递该授权响应 URL 以获取access token::

access_token = oauth2_user_handler.fetch_token(
    "Authorization Response URL here"
)

你可以在初始化 Client 时,把access token 传递给它:

client = tweepy.Client("Access Token here")

3-legged OAuth

本节补充了 3-legged OAuth flow documentation.

要作为你开发者账号以外的身份进行认证, 你需要通过 3-legged OAuth 流获取他们的access tokens。

首先,你需要在 Twitter Developer Portal Projects & Apps page 页面中打开OAuth 1.0 。为此, 你需要提供 Callback / Redirect URI / URL。

然后, 你需要在同样的页面中 Twitter Developer Portal Projects & Apps page 找到应用的 consumer key 和 secret。

初始化 OAuth1UserHandler:

import tweepy

oauth1_user_handler = tweepy.OAuth1UserHandler(
    "API / Consumer Key here", "API / Consumer Secret here",
    callback="Callback / Redirect URI / URL here"
)

然后,获取授权链接:

print(oauth1_user_handler.get_authorization_url())

登录推特, 你可以在该链接上设置 signin_with_twitter 参数:

print(oauth1_user_handler.get_authorization_url(signin_with_twitter=True))

这可用于让用户验证您的应用程序。一旦他们这样做了,他们将被重定向到你提供的 Callback / Redirect URI / URL , 带有 oauth_tokenoauth_verifier 参数。

你可以使用 verifier 获取 access token 和 secret:

access_token, access_token_secret = oauth1_user_handler.get_access_token(
    "Verifier (oauth_verifier) here"
)

如果你需要重新初始化 OAuth1UserHandler, 你可以在使用 verifier 前,通过设置 token 和 secret 来获得access token 和access secret:

request_token = oauth1_user_handler.request_token["oauth_token"]
request_secret = oauth1_user_handler.request_token["oauth_token_secret"]

new_oauth1_user_handler = tweepy.OAuth1UserHandler(
    "API / Consumer Key here", "API / Consumer Secret here",
    callback="Callback / Redirect URI / URL here"
)
new_oauth1_user_handler.request_token = {
    "oauth_token": "Request Token (oauth_token) here",
    "oauth_token_secret": request_secret
}
access_token, access_token_secret = (
    new_oauth1_user_handler.get_access_token(
        "Verifier (oauth_verifier) here"
    )
)

否则, 只需使用 OAuth1UserHandler 的旧实例即可。

你能使用 OAuth1UserHandler 的实例去初始化 API:

api = tweepy.API(oauth1_user_handler)

你也能使用 access_tokenaccess_token_secret 的实例 OAuth1UserHandler 去初始化 API:

auth = tweepy.OAuth1UserHandler(
   "API / Consumer Key here", "API / Consumer Secret here",
   "Access Token here", "Access Token Secret here"
)
api = tweepy.API(auth)

你也能直接使用 access_tokenaccess_token_secret 初始化 Client

client = tweepy.Client(
    consumer_key="API / Consumer Key here",
    consumer_secret="API / Consumer Secret here",
    access_token="Access Token here",
    access_token_secret="Access Token Secret here"
)

PIN-based OAuth

本节补充了 PIN-based OAuth documentation.

通过将 callback 参数设置为 "oob" 可以使用 PIN-based OAuth flow:

import tweepy

oauth1_user_handler = tweepy.OAuth1UserHandler(
    "API / Consumer Key here", "API / Consumer Secret here",
    callback="oob"
)

你可以通过同样的方式获取授权链接:

print(oauth1_user_handler.get_authorization_url())

当用户使用此链接进行身份验证时, 将向他们提供一个PIN码。 你能验证这个PIN

verifier = input("Input PIN: ")
access_token, access_token_secret = oauth1_user_handler.get_access_token(
    verifier
)

参考

class tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token=None, access_token_secret=None, callback=None)

OAuth 1.0a User Context authentication handler

Changed in version 4.5: Renamed from OAuthHandler

get_authorization_url(signin_with_twitter=False, access_type=None)

获取将用户重定向到的授权链接

get_access_token(verifier=None)

After user has authorized the app, get access token and secret with verifier

set_access_token(key, secret)

Deprecated since version 4.5: Set through initialization instead.

class tweepy.OAuthHandler(consumer_key, consumer_secret, access_token=None, access_token_secret=None, callback=None)

Alias for OAuth1UserHandler

Deprecated since version 4.5: Use OAuth1UserHandler instead.

class tweepy.OAuth2AppHandler(consumer_key, consumer_secret)

OAuth 2.0 Bearer Token (App-Only) using API / Consumer key and secret authentication handler

Changed in version 4.5: Renamed from AppAuthHandler

class tweepy.AppAuthHandler(consumer_key, consumer_secret)

Alias for OAuth2AppHandler

Deprecated since version 4.5: Use OAuth2AppHandler instead.

class tweepy.OAuth2BearerHandler(bearer_token)

Bases: requests.auth.AuthBase

OAuth 2.0 Bearer Token (App-Only) authentication handler

New in version 4.5.

class tweepy.OAuth2UserHandler(*, client_id, redirect_uri, scope, client_secret=None)

Bases: requests_oauthlib.oauth2_session.OAuth2Session

OAuth 2.0 Authorization Code Flow with PKCE (User Context) authentication handler

New in version 4.5.

Construct a new OAuth 2 client session.

Parameters
  • client_id – Client id obtained during registration

  • clientoauthlib.oauth2.Client to be used. Default is WebApplicationClient which is useful for any hosted application but not mobile or desktop.

  • scope – List of scopes you wish to request access to

  • redirect_uri – Redirect URI you registered as callback

  • token – Token dictionary, must include access_token and token_type.

  • state – State string used to prevent CSRF. This will be given when creating the authorization url and must be supplied when parsing the authorization response. Can be either a string or a no argument callable.

  • kwargs – Arguments to pass to the Session constructor.

Auto_refresh_url

Refresh token endpoint URL, must be HTTPS. Supply this if you wish the client to automatically refresh your access tokens.

Auto_refresh_kwargs

Extra arguments to pass to the refresh token endpoint.

Token_updater

Method with one argument, token, to be used to update your token database on automatic token refresh. If not set a TokenUpdated warning will be raised when a token has been refreshed. This warning will carry the token in its token argument.

get_authorization_url()

Get the authorization URL to redirect the user to

fetch_token(authorization_response)

After user has authorized the app, fetch access token with authorization response URL