Skip to content

Instantly share code, notes, and snippets.

@Johnetordoff
Created February 20, 2024 14:36
Show Gist options
  • Save Johnetordoff/2ef9eb047b3faa6c730051193862bf61 to your computer and use it in GitHub Desktop.
Save Johnetordoff/2ef9eb047b3faa6c730051193862bf61 to your computer and use it in GitHub Desktop.
Oauth Client
from flask import Flask, request, redirect, session
import requests
import uuid
app = Flask(__name__)
app.secret_key = 'your_secret_key' # Needed for session management
# Register with the oauth provider and change the credentials to match.
CLIENT_ID = '<change>'
CLIENT_SECRET = '<change>'
AUTHORIZATION_URL = 'http://localhost:5000/authorize' # Mock provider's authorization URL
TOKEN_URL = 'http://localhost:5000/token' # Mock provider's token URL
REDIRECT_URI = 'http://localhost:8000/callback' # Your callback URL
@app.route('/')
def home():
# Generate a random state value for CSRF protection
state = str(uuid.uuid4())
session['oauth_state'] = state
# Redirect user to OAuth provider's authorization page
return redirect(
f'{AUTHORIZATION_URL}?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&state={state}'
)
@app.route('/callback')
def callback():
# Verify the state parameter for CSRF protection
if request.args.get('state') != session.pop('oauth_state', None):
return 'State mismatch. Potential CSRF attack.', 400
code = request.args.get('code')
if not code:
return 'Authorization failed.', 400
# Exchange the authorization code for an access token
token_response = requests.post(TOKEN_URL, data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
}).json()
access_token = token_response.get('access_token')
if not access_token:
return 'Failed to obtain access token.', 400
# Use the access token to access protected resources
# For example, a user info endpoint on the OAuth provider
# response = requests.get(PROTECTED_RESOURCE_URL, headers={'Authorization': f'Bearer {access_token}'})
return 'Authentication successful. Access token obtained.'
if __name__ == '__main__':
app.run(port=8000, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment