- Flaskを使用したTwitterログイン連携についてメモする。
- Google連携やFacebook連携を試したもののTwitter版
大まかな処理の流れ
-
リクエストトークンを取得する。※GoogleやFacebookなどと異なる点。
-
リクエストトークンを指定してTwitterへ認可リクエスト(Authorization Request)を行う。
-
ユーザー認証/同意を行い、認可レスポンスを受け取る。
-
認可レスポンスを使ってトークンリクエストを行う。
事前準備
-
Twitterデベロッパーコンソールからアプリケーションを登録する。
- API Key and Secretの取得する。
- コールバック(リダイレクト)URIの設定する。
- 今回はhttp://localhost:5000/callback を設定する。
実装
- アクセストークンを取得するまでのコード
from requests_oauthlib import OAuth1Session
from flask import Flask, jsonify, request, redirect
import urllib.parse as parse
# App Info
api_key = "<YOUR API KEY>"
api_secret = "<YOUR API SECRET>"
# Twitter Endpoint
twitter_base_url = 'https://api.twitter.com'
authorization_endpoint = twitter_base_url + '/oauth/authenticate'
request_token_endpoint = twitter_base_url + '/oauth/request_token'
token_endpoint = twitter_base_url + '/oauth/access_token'
app = Flask(__name__)
@app.route("/login")
def login():
# 1.リクエストトークンを取得する。
# (Step 1: Obtaining a request token:https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter)
twitter = OAuth1Session(api_key, api_secret)
oauth_callback = request.args.get('oauth_callback')
res = twitter.post(request_token_endpoint, params={
'oauth_callback': oauth_callback})
request_token = dict(parse.parse_qsl(res.content.decode("utf-8")))
oauth_token = request_token['oauth_token']
# 2.リクエストトークンを指定してTwitterへ認可リクエスト(Authorization Request)を行う。
# (Step 2: Redirecting the user:https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter#tab2)
return redirect(authorization_endpoint+'?{}'.format(parse.urlencode({
'oauth_token': oauth_token
})))
@app.route("/callback")
def callback():
# 3.ユーザー認証/同意を行い、認可レスポンスを受け取る。
oauth_verifier = request.args.get('oauth_verifier')
oauth_token = request.args.get('oauth_token')
# 4.認可レスポンスを使ってトークンリクエストを行う。
# (Step 3: Converting the request token to an access token:https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter#tab3)
twitter = OAuth1Session(
api_key,
api_secret,
oauth_token
)
res = twitter.post(
token_endpoint,
params={'oauth_verifier': oauth_verifier}
)
access_token = dict(parse.parse_qsl(res.content.decode("utf-8")))
return jsonify(access_token)
if __name__ == "__main__":
app.run(debug=True)