直接上代码
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wraps
app = Flask(__name__)
# 这是一个示例密钥,实际应用中应该使用一个复杂且随机的密钥
app.config['SECRET_KEY'] = 'your_secret_key'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'Authorization' in request.headers:
auth_header = request.headers['Authorization']
if auth_header.startswith('Bearer '):
token = auth_header.split(" ")[1] # 分割"Bearer "和token
if not token:
return jsonify({'message': 'Token is missing!'}), 403
try:
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
except:
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 == 'password':
token = jwt.encode({
'user': auth.username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
}, 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)
测试,登录,获取token
curl -u username:password http://127.0.0.1:5000/login
返回
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y"
}
用token 测试/protected
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y" http://127.0.0.1:5000/protected
返回信息
{
"message": "This is only available for people with valid tokens."
}
文章来源:https://www.toymoban.com/news/detail-835787.html
chatgpt写的代码文章来源地址https://www.toymoban.com/news/detail-835787.html
到了这里,关于python3 Flask jwt 简易token认证实例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!