Skip to content

Instantly share code, notes, and snippets.

@Johnetordoff
Created February 20, 2024 14:35
Show Gist options
  • Save Johnetordoff/60bf10f56576d59df4fb7e87979146e8 to your computer and use it in GitHub Desktop.
Save Johnetordoff/60bf10f56576d59df4fb7e87979146e8 to your computer and use it in GitHub Desktop.
Oauth Provider
from flask import Flask, request, jsonify, redirect, render_template_string
from uuid import uuid4
app = Flask(__name__)
# In-memory database simulation
clients = {} # Registered clients {client_id: client_secret}
auth_codes = {} # Authorization codes {code: client_id}
tokens = {} # Tokens {access_token: client_id}
@app.route('/register', methods=['POST'])
def register_client():
client_id = str(uuid4())
client_secret = str(uuid4())
clients[client_id] = client_secret
return jsonify({'client_id': client_id, 'client_secret': client_secret})
@app.route('/authorize')
def authorize():
client_id = request.args.get('client_id')
redirect_uri = request.args.get('redirect_uri')
# Simple validation of client_id and redirect_uri
if client_id in clients and redirect_uri:
# Generate authorization code
code = str(uuid4())
auth_codes[code] = client_id
# Redirect back to the client with the code
return redirect(f'{redirect_uri}?code={code}')
else:
return 'Invalid client_id or redirect_uri', 400
@app.route('/token', methods=['POST'])
def token():
client_id = request.form.get('client_id')
client_secret = request.form.get('client_secret')
code = request.form.get('code')
print(request.form)
# Validate client_id, client_secret, and code
if client_id in clients and clients[client_id] == client_secret and code in auth_codes:
if auth_codes[code] == client_id:
# Generate access token
access_token = str(uuid4())
tokens[access_token] = client_id
return jsonify({'access_token': access_token})
return 'Invalid request', 400
@app.route('/data')
def data():
return jsonify(
{
'clients': clients,
'auth_codes': auth_codes,
'token': tokens,
}
)
@app.route('/')
def home():
html_content = """
<html>
<head>
<title>OAuth Server Simulation</title>
</head>
<body>
<h1>OAuth Server Simulation</h1>
<h2>Register Client</h2>
<form method="post" action="/register">
<input type="submit" value="Register New Client">
</form>
<h2>Authorize</h2>
<form method="get" action="/authorize">
<input type="text" name="client_id" placeholder="Client ID">
<input type="text" name="redirect_uri" placeholder="Redirect URI">
<input type="submit" value="Authorize">
</form>
<h2>Get Token</h2>
<form method="post" action="/token">
<input type="text" name="client_id" placeholder="Client ID">
<input type="text" name="client_secret" placeholder="Client Secret">
<input type="text" name="code" placeholder="Authorization Code">
<input type="submit" value="Get Token">
</form>
</body>
</html>
"""
return render_template_string(html_content)
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment