Flask实现JWT简单验证

周和歌
2023-12-01

使用koa和php springboot开发的都知道中间件实现验证,flask是通过python的装饰器实现。

下面记录实现过程和遇到的方法处理:

1. 安装插件flask_jwt_extended

pipenv install flask_jwt_extended

 

2.懒加载实现

 jwt=JWTManager()

def create_app():

....

jwt.init_app(app)

2.1 配置文件

JWT_SECRET_KEY='me1UMiUFhSUjqxSs'

JWT_ACCESS_TOKEN_EXPIRES=3600 #过期时间1小时

3. 生成token  POST http://localhost:5000/api/v1/login

@web.route('/login',methods=['POST'])
def login():
    user=request.get_json()
    # password=request.json.get('password')
    token=create_access_token(identity=user)

    return token,200

>>>返回示例:

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 305
Server: Werkzeug/2.0.1 Python/3.9.5
Date: Mon, 14 Jun 2021 05:28:10 GMT

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyMzY0ODQ5MCwianRpIjoiZThmOGFjMTgtYzkxNS00ODNiLWJhN2YtYTNjNjVlZjE1OGI0IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6eyJuYW1lIjoiQm9iIiwicGFzc3dvcmQiOiIxMjM0NTYifSwibmJmIjoxNjIzNjQ4NDkwLCJleHAiOjE2MjM2NDkzOTB9.w2b456WN55TQHGXAJIn_HWD2ppnlmf1Vk732EybGP6U

3.1 请求示例

 


POST http://{{host}}/api/v1/login
Content-Type: application/json


{
    "name":"Bob",
    "password":"123456"
}

3.2 JWT验证

@web.route('/hash')
@jwt_required(optional=False)
def hash():
    return generate_password_hash('123456'),200

注意如果不加optional=False会出现错误

TypeError: wrapper() missing 1 required positional argument: 'fn'

3.3 请求示例

### /api/v1/hash 密码加密实现
GET http://{{host}}/api/v1/hash
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyMzY0NjY1MiwianRpIjoiMGZiMzJiYTctZTQ2NC00YTAwLWEyNjMtODgxMDVlM2FiY2FiIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6eyJuYW1lIjoiQm9iIiwicGFzc3dvcmQiOiIxMjM0NTYifSwibmJmIjoxNjIzNjQ2NjUyLCJleHAiOjE2MjM2NDc1NTJ9.QdmHdBx59UVyFMxLD3RdYDGPIy9nnUCxnlGOQ2h2wyA

3.4 返回示例:

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 102
Server: Werkzeug/2.0.1 Python/3.9.5
Date: Mon, 14 Jun 2021 05:38:28 GMT

pbkdf2:sha256:260000$oMUeC11zbAiLNUK9$411127cc6b3ebe515e897aa79be4f794801cfb31c48006251432ba008e824ae0

 

 类似资料: