当前位置:   article > 正文

python3 Flask jwt 简易token认证实例_爬虫 flask 简单的密钥验证

爬虫 flask 简单的密钥验证

 直接上代码

  1. from flask import Flask, jsonify, request, make_response
  2. import jwt
  3. import datetime
  4. from functools import wraps
  5. app = Flask(__name__)
  6. # 这是一个示例密钥,实际应用中应该使用一个复杂且随机的密钥
  7. app.config['SECRET_KEY'] = 'your_secret_key'
  8. def token_required(f):
  9. @wraps(f)
  10. def decorated(*args, **kwargs):
  11. token = None
  12. if 'Authorization' in request.headers:
  13. auth_header = request.headers['Authorization']
  14. if auth_header.startswith('Bearer '):
  15. token = auth_header.split(" ")[1] # 分割"Bearer "和token
  16. if not token:
  17. return jsonify({'message': 'Token is missing!'}), 403
  18. try:
  19. data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
  20. except:
  21. return jsonify({'message': 'Token is invalid!'}), 403
  22. return f(*args, **kwargs)
  23. return decorated
  24. @app.route('/unprotected')
  25. def unprotected():
  26. return jsonify({'message': 'Anyone can view this!'})
  27. @app.route('/protected')
  28. @token_required
  29. def protected():
  30. return jsonify({'message': 'This is only available for people with valid tokens.'})
  31. @app.route('/login')
  32. def login():
  33. auth = request.authorization
  34. if auth and auth.password == 'password':
  35. token = jwt.encode({
  36. 'user': auth.username,
  37. 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
  38. }, app.config['SECRET_KEY'])
  39. return jsonify({'token': token})
  40. return make_response('Could not verify!', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
  41. if __name__ == '__main__':
  42. app.run(debug=True)

测试,登录,获取token

  1. curl -u username:password http://127.0.0.1:5000/login
  2. 返回
  3. {
  4. "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y"
  5. }

 

用token 测试/protected

  1. curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y" http://127.0.0.1:5000/protected
  2. 返回信息
  3. {
  4. "message": "This is only available for people with valid tokens."
  5. }

 

chatgpt写的代码

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/570714
推荐阅读
相关标签
  

闽ICP备14008679号