JWT_REFRESH_TOKEN_EXPIRES 怎么使用,给我写一个例子
时间: 2023-05-13 10:05:10 浏览: 125
JWT_REFRESH_TOKEN_EXPIRES 是一个用于设置 JWT 刷新令牌过期时间的变量,它通常与 JWT_ACCESS_TOKEN_EXPIRES 一起使用。下面是一个使用 Flask-JWT-Extended 扩展的例子:
```python
from flask import Flask
from flask_jwt_extended import JWTManager, create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret' # 设置 JWT 密钥
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 3600 # 设置访问令牌过期时间为 1 小时
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = 604800 # 设置刷新令牌过期时间为 1 周
jwt = JWTManager(app)
# 用户登录,生成访问令牌和刷新令牌
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username', None)
password = request.json.get('password', None)
if username != 'admin' or password != 'admin':
return jsonify({'msg': 'Invalid username or password'}), 401
access_token = create_access_token(identity=username)
refresh_token = create_refresh_token(identity=username)
return jsonify({'access_token': access_token, 'refresh_token': refresh_token}), 200
# 使用访问令牌访问受保护的资源
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
current_user = get_jwt_identity()
return jsonify({'msg': f'Hello, {current_user}!'}), 200
# 使用刷新令牌刷新访问令牌
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
current_user = get_jwt_identity()
access_token = create_access_token(identity=current_user)
return jsonify({'access_token': access_token}), 200
if __name__ == '__main__':
app.run()
```
在上面的例子中,我们设置了 JWT_REFRESH_TOKEN_EXPIRES 为 1 周,表示刷新令牌在 1 周后过期。当用户登录成功后,我们生成了一个访问令牌和一个刷新令牌,并将它们返回给客户端。当客户端使用访问令牌访问受保护的资源时,我们使用 @jwt_required 装饰器来保护该路由,只有在客户端提供有效的访问令牌时才能访问。当客户端的访问令牌过期时,客户端可以使用刷新令牌来获取新的访问令牌,我们使用 @jwt_refresh_token_required 装饰器来保护刷新令牌路由,只有在客户端提供有效的刷新令牌时才能刷新访问令牌。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)