How to fake JWT Authorization outside of request context and get current identity? How to fake JWT Authorization outside of request context and get current identity? flask flask

How to fake JWT Authorization outside of request context and get current identity?


If you are writing unit tests, using mock can be helpful. For jwt authorization with flask-jwt-extended you can patch the verify_jwt_in_request method which is called from the jwt_required decorator. Then you can also patch the get_jwt_identity function to return a test username. For example:

from unittest.mock import patch@patch('path.to.some.code.get_jwt_identity')@patch('flask_jwt_extended.view_decorators.verify_jwt_in_request')def test_some_code(mock_jwt_required, mock_jwt_identity):    mock_jwt_identity.return_value = 'user1'    # Test jwt protected endpoint

Note: This patch is specific to latest package version flask-jwt-extended==3.21.0. The code may change with new versions.


If you truly want to unit test you need to unit test one function at a time. This is true test driven development in my opinion. So first write tests for create then load and so on. Use patching to mock the functionality of calls to other functions.


Question from a long time ago but here is the solution for further readers.

You need to activate the app_context, then the request_context and finally call the function decorator is calling, which is verify_jwt_in_request:

fake_payload = {}with client.application.app_context():    with client.application.test_request_context('/listings', headers={'Authorization': 'Bearer ' + access_token}):        verify_jwt_in_request()        create(fake_payload)

and now you have your current_user set