1

I am using Python 3.9 and the Flask-JWT-Extended PyPi package in my application. I am writing some test cases and when I POST to the endpoint I am testing with a proper-looking Bearer token, I get an HTTP 422 'Unprocessable Entity'. Google is not turning up an answer. How can I fix this?

# Do the Bearer login
data = {
    'username': app.username,
    'password': app.password,
}
tokenResponse = client.post("/login", json=data)
assert tokenResponse.content_type == 'application/json'
assert tokenResponse.json['access_token']

And shortly after, in the same test method, I try to POST to the actual endpoint:

print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print({"Authorization": f"JWT {tokenResponse.json['access_token']}"})
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

response = client.post(endpoint, buffered=False,
                               content_type='multipart/form-data',
                               data=data,headers={"Authorization": f"JWT {tokenResponse.json['access_token']}"})

Here is the token printout:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{'Authorization': 'JWT eyJ0eXAiOiJKV1QilCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTI0Nzk5NzAsIm5iZiI6MTYxMjQ3OTk3MCwianRpIjoiYTQyZjU1NmUtYjQ2MS00NTNiLThkM2ItYjk1MmIzYzAwZjc0IiwiZXhwIjoxNjeyNDgwMDMwLCJpZGVudGl0eSI6IlNlbnNvbml4QXBpVXNlciIsImZyZXNoIjpmYWxzZSwidHlwZSI6ImFjY2VzcyJ9.IYrgg2e9VxhLFH0_kwQbmoHKI1wKsKfm3cpK3XZmqyY'}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the traceback.

            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print({"Authorization": f"JWT {tokenResponse.json['access_token']}"})
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    
            response = client.post(endpoint, buffered=False,
                                       content_type='multipart/form-data',
                                       data=data,headers={"Authorization": f"JWT {tokenResponse.json['access_token']}"})
>           assert response.status_code == 200
E           assert 422 == 200
E            +  where 422 = <Response streamed [422 UNPROCESSABLE ENTITY]>.status_code

../tests/test_endpoints.py:153: AssertionError

1 Answer 1

2

First suggestion, if you look at the response.get_json() it should give you a helpful error message for why the 422 was thrown (invalid audience, jwt verification failed, etc). That might help point you in the right direction.

Here is an example of a working spec that creates and passes a JWT in via headers if it helps:

import pytest

from flask import Flask
from flask import  jsonify

from flask_jwt_extended import JWTManager
from flask_jwt_extended import jwt_required
from flask_jwt_extended import create_access_token


@pytest.fixture(scope="function")
def app():
    app = Flask(__name__)
    app.config["JWT_SECRET_KEY"] = "foobarbaz"
    JWTManager(app)

    @app.route("/login", methods=["POST"])
    def login():
        return jsonify(access_token=create_access_token("test_user"))

    @app.route("/protected", methods=["GET"])
    @jwt_required
    def access_protected():
        return jsonify(foo="bar")

    return app


def test_default_headers(app):
    test_client = app.test_client()

    response = test_client.post("/login")
    access_token = response.get_json()["access_token"]

    access_headers = {"Authorization": "Bearer {}".format(access_token)}
    response = test_client.get("/protected", headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {"foo": "bar"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.