[英]Flask JWT : get_jwt_identity() without @jwt_required always return Non
I am building a Flask JWT extended application, and here is what I want to do:我正在构建一个 Flask JWT 扩展应用程序,这就是我想要做的:
I have and endpoint open to everyone (ie no decorator @jwt_required, everyone can access the link)我有对所有人开放的端点(即没有装饰器@jwt_required,每个人都可以访问链接)
but if someone access this link with an authentication, I want to be able to get back his identity, something like that:但是如果有人通过身份验证访问此链接,我希望能够取回他的身份,例如:
@bp.route('/test', methods=('GET', 'POST'))
def test() -> str:
identity = get_jwt_identity()
print(a)
if identity is not None:
# do something
else:
# do other stuff
the issue is that without the decorator, get_jwt_identity always return None问题是没有装饰器, get_jwt_identity 总是返回 None
Is there a way to accomplish that?有没有办法做到这一点?
Thanks谢谢
If you are using the 4.xx version, use @jwt_required(optional=True)
.如果您使用的是 4.xx 版本,请使用
@jwt_required(optional=True)
。 If you are still on the 3.xx version use @jwt_optional
如果您仍在使用 3.xx 版本,请使用
@jwt_optional
If you want to decode custom access token on unprotected endpoint.如果您想在不受保护的端点上解码自定义访问令牌。 you need to use the
decode_token
from flask-jwt-extended
您需要使用来自
flask-jwt-extended
的decode_token
from flask_jwt_extended import decode_token
def post(self):
data = ResetPassword.parser.parse_args()
reset_token = data['reset_token']
decoded_token = decode_token(reset_token)['sub']
the sub
refers to `identity when you're creating a token from sub
指的是当您创建令牌时的身份
access_token = create_access_token(identity=user.get_id())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.