Created
September 25, 2023 18:52
-
-
Save yarlson/b383b582e74c89b84e8098c5da85211a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from flask import Flask, request, redirect | |
from requests_oauthlib import OAuth1Session | |
import webbrowser | |
app = Flask(__name__) | |
# Your API Key and API Secret Key from the Twitter Developer Dashboard | |
API_KEY = os.environ.get('CONSUMER_KEY') | |
API_SECRET_KEY = os.environ.get('CONSUMER_SECRET') | |
# Twitter endpoints | |
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' | |
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' | |
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' | |
oauth_callback = 'http://localhost:8080/callback' | |
initial_oauth = OAuth1Session(API_KEY, client_secret=API_SECRET_KEY, callback_uri=oauth_callback) | |
@app.route('/') | |
def start(): | |
oauth = OAuth1Session(API_KEY, client_secret=API_SECRET_KEY, callback_uri=oauth_callback) | |
authorization_url = oauth.authorization_url(AUTHORIZATION_URL) | |
return redirect(authorization_url) | |
@app.route('/callback') | |
def callback(): | |
oauth_response = initial_oauth.parse_authorization_response(request.url) | |
oauth_token = oauth_response.get('oauth_token') | |
oauth_verifier = oauth_response.get('oauth_verifier') | |
oauth = OAuth1Session( | |
API_KEY, | |
client_secret=API_SECRET_KEY, | |
resource_owner_key=oauth_token, | |
verifier=oauth_verifier | |
) | |
tokens = oauth.fetch_access_token(ACCESS_TOKEN_URL) | |
return tokens | |
if __name__ == "__main__": | |
webbrowser.open("http://localhost:8080/") | |
app.run(port=8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Twitter OAuth1 Authentication with Flask
This script sets up a simple Flask server that helps you authenticate with Twitter using the OAuth1 protocol and obtain the access token and token secret.
Prerequisites
Installation
Install the Dependencies
Install the necessary Python packages using
pip
:Configuration
Set up Twitter Consumer Keys
Keys and Tokens
tab, thenConsumer Keys
,Generate
Environment Variables
Before running the script, you need to set up a few environment variables. You can do this manually or use a
.env
file.For manual setup:
Running the Script
Once you have set up the necessary configurations, you can run the script: