LoginSignup
3
6

More than 3 years have passed since last update.

Flaskを使用したTwitter ログイン連携メモ

Posted at
  • Flaskを使用したTwitterログイン連携についてメモする。

大まかな処理の流れ

  1. リクエストトークンを取得する。※GoogleやFacebookなどと異なる点。

  2. リクエストトークンを指定してTwitterへ認可リクエスト(Authorization Request)を行う。

  3. ユーザー認証/同意を行い、認可レスポンスを受け取る。

  4. 認可レスポンスを使ってトークンリクエストを行う。

事前準備

実装

  • アクセストークンを取得するまでのコード
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)

参考情報

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6