33
loading...
This website collects cookies to deliver better user experience
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisthesecretkey'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.args.get('token')
if not token:
return jsonify({'message' : 'Token is missing!'}), 403
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms="HS256")
except Exception as inst:
print(inst)
return jsonify({'message' : 'Token is invalid!'}), 403
return f(*args, **kwargs)
return decorated
@app.route('/unprotected')
def unprotected():
return jsonify({'message' : 'Anyone can view this!'})
@app.route('/protected')
@token_required
def protected():
return jsonify({'message' : 'This is only available for people with valid tokens.'})
@app.route('/login')
def login():
auth = request.authorization
if auth and auth.password == 'Passw0rd':
token = jwt.encode({'user' : auth.username, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(minutes=15)}, app.config['SECRET_KEY'], algorithm="HS256")
return jsonify({'token' : token})
return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
if __name__ == '__main__':
app.run(debug=True)
$ python3 api.py
* Serving Flask app "api" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 241-307-717
http://127.0.0.1:5000/unprotected
http://127.0.0.1:5000/protected
http://127.0.0.1:5000/login
http://127.0.0.1:5000/protected?token=invalidtoken
http://127.0.0.1:5000/protected?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiYWxpIiwiZXhwIjoxNjI5MTg4NDMwfQ.ni3Soivc1a4vKyI3_xpDyb1-RV3iDQ4QMtS3FhXijog