Skip to content

Instantly share code, notes, and snippets.

@Xophmeister
Last active August 29, 2015 14:19
Show Gist options
  • Save Xophmeister/89f64fff308682e5203e to your computer and use it in GitHub Desktop.
Save Xophmeister/89f64fff308682e5203e to your computer and use it in GitHub Desktop.
Xiongxiong token authentication in Python/Flask
from datetime import datetime
from functools import wraps
from flask import Flask, request, Response
app = Flask(__name__)
# Read in the private key and instantiate xiongxiong
with open('privateKeyFile') as keyFile:
key = keyFile.read()
from xiongxiong import Xiongxiong
xiongxiong = Xiongxiong(key)
# Token authentication decorator
def authenticateToken(f):
@wraps(f)
def _(*args, **kwargs):
try:
# Unpack Authorization request header
method, payload = request.headers['Authorization'].split()
method = method.lower()
# Decode the authorisation payload
if method == 'bearer':
# Decode bearer token
token = xiongxiong(payload)
elif method == 'basic':
# Decode basic auth pair
token = xiongxiong(request.authorization.username.strip(),
request.authorization.password.strip())
else:
raise Exception
# Are we good to go?
if token.valid:
return f(token = token, *args, **kwargs)
else:
raise Exception
except:
# Unauthorised
return Response('Cannot authenticate :(\n',
401, {'WWW-Authenticate': 'Basic'})
return _
@app.route('/')
@authenticateToken
def hello(token):
data = (token.data, (token.expiration - datetime.now()).seconds)
return 'You\'re in :)\nPayload: %s\nExpires: T-%d seconds\n' % data
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment