Last active
October 26, 2018 18:50
-
-
Save shahbaz17/9ba7a14aa402622808a8f4dc87e43e8e to your computer and use it in GitHub Desktop.
Flask App | JWT implementation
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
| from flask import Flask, jsonify, request, make_response | |
| import jwt | |
| import datetime | |
| from functools import wraps | |
| app = Flask(__name__) | |
| app.config['SECRET_KEY'] = 'indonesia' | |
| # Token Decorator | |
| 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']) | |
| except: | |
| return jsonify({'message' : 'Token is invalid!'}), 403 | |
| return f(*args, **kwargs) | |
| return decorated | |
| # Unprotected Route and function | |
| @app.route('/unprotected') | |
| def unprotected(): | |
| return jsonify({'message' : 'Anyone can view this.'}) | |
| # Protected Route and function | |
| @app.route('/protected') | |
| @token_required | |
| def protected(): | |
| return jsonify({'message' : 'Only available to people with valid tokens.'}) | |
| # Login Route and function | |
| @app.route('/login') | |
| def login(): | |
| auth = request.authorization | |
| if auth and auth.password == 'pyconid': | |
| token = jwt.encode({'user': auth.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=50)}, app.config['SECRET_KEY']) | |
| return jsonify({'token' : token}) | |
| return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm:"Login Required"'}) | |
| if __name__ == "__main__": | |
| app.run(debug=True) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirement: Python 2
Open terminal and type following
python flaskapp.pyNow open Firefox Browser and head over to http://127.0.0.1:5000/login
Type
username='PyCon' and password='pyconid'when pop up window appearsYou will get token something like
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidGVzdCIsImV4cCI6MTU0MDU3OTU3MH0.58ZK-lN3oIhxW_ODiMwwOA1kZyigBLhFZbXExW4UkVUCopy the token and head over to http://127.0.0.1:5000/protected
You will see a message Token is missing
But when visiting http://127.0.0.1:5000/protected?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidGVzdCIsImV4cCI6MTU0MDU3OTU3MH0.58ZK-lN3oIhxW_ODiMwwOA1kZyigBLhFZbXExW4UkVU
You will receive a message Only available to people with valid tokens. and
again visit the same link after 50 seconds, you will receive a message Token is invalid!