Flask JWT : get_jwt_identity() without @jwt_required always return Non

Viewed 1078

I am building a Flask JWT extended application, and here is what I want to do :

I have and endpoint open to everyone (i.e. no decorator @jwt_required, everyone can access the link)

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

Is there a way to accomplish that?

Thanks

2 Answers

If you are using the 4.x.x version, use @jwt_required(optional=True). If you are still on the 3.x.x version use @jwt_optional

If you want to decode custom access token on unprotected endpoint. you need to use the decode_token from flask-jwt-extended

 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

    access_token = create_access_token(identity=user.get_id())
Related