· 9 years ago · Dec 13, 2016, 05:35 PM
1from flask import Flask, request
2from functools import wraps
3
4import jwt
5app = Flask(__name__)
6
7SECRET_KEY = "secret"
8
9def token_required(func):
10 @wraps(func)
11 def decorated_function(post_id):
12 try:
13 token = request.headers.get('Authorization').replace("Bearer", "").strip()
14 payload = jwt.decode(token, SECRET_KEY)
15 return func(post_id)
16 except jwt.InvalidTokenError:
17 return "unvalid token"
18 return decorated_function
19
20
21@app.route('/post/<int:post_id>')
22@token_required
23def show_post(post_id):
24 return ""
25
26# Lauches the API in port 5000.
27if __name__ == '__main__':
28 app.run(host='0.0.0.0', port=5000, debug=False)
29
30
31"""
32command: curl http://0.0.0.0:5000/post/3 --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwb3N0Ijp0cnVlfQ.r2ZdOE5ttmu8Zhk3iZ25BDojn19JNQ-mnfaX11eFNRM"
33"""