python3 Flask jwt 简易token认证实例

直接上代码

复制代码
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."
}

chatgpt写的代码

相关推荐
雕刻刀8 分钟前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
何双新10 分钟前
Odoo 技术演进全解析:从 Widget 到 Owl,从 Old API 到声明式 ORM
python
山川行37 分钟前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
星辰徐哥42 分钟前
C语言游戏开发:Pygame、SDL、OpenGL深度解析
c语言·python·pygame
武超杰44 分钟前
Spring Boot入门教程
java·spring boot·后端
xcLeigh1 小时前
Python入门:Python3基础练习题详解,从入门到熟练的 25 个实例(六)
开发语言·python·教程·python3·练习题
IT 行者1 小时前
Spring Boot 集成 JavaMail 163邮箱配置详解
java·spring boot·后端
不懒不懒1 小时前
安装python3.9.7和pycharm-community-2022.3.2.exe以及linux
linux·ide·python·pycharm
Jasonakeke1 小时前
我的编程来时路
java·c++·python
Yvonne爱编码1 小时前
Java 中的 hashCode () 与 equals () 核心原理、契约规范、重写实践与面试全解
java·开发语言·数据结构·python·hash