Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow customizing the JSON error response's message key #160

Merged
merged 1 commit into from
Jul 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ General Options:
Defaults to ``'user_claims'``.
``JWT_CLAIMS_IN_REFRESH_TOKEN`` If user claims should be included in refresh tokens.
Defaults to ``False``.
``JWT_ERROR_MESSAGE_KEY`` The key of the error message in a JSON error response when using
the default error handlers.
Defaults to ``'msg'``.
================================= =========================================


Expand Down
4 changes: 4 additions & 0 deletions flask_jwt_extended/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ def user_claims_in_refresh_token(self):
def exempt_methods(self):
return {"OPTIONS"}

@property
def error_msg_key(self):
return current_app.config['JWT_ERROR_MESSAGE_KEY']

@property
def json_encoder(self):
return current_app.json_encoder
Expand Down
16 changes: 9 additions & 7 deletions flask_jwt_extended/default_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"""
from flask import jsonify

from flask_jwt_extended.config import config


def default_user_claims_callback(userdata):
"""
Expand Down Expand Up @@ -37,7 +39,7 @@ def default_expired_token_callback():
By default, if an expired token attempts to access a protected endpoint,
we return a generic error message with a 401 status
"""
return jsonify({'msg': 'Token has expired'}), 401
return jsonify({config.error_msg_key: 'Token has expired'}), 401


def default_invalid_token_callback(error_string):
Expand All @@ -47,7 +49,7 @@ def default_invalid_token_callback(error_string):

:param error_string: String indicating why the token is invalid
"""
return jsonify({'msg': error_string}), 422
return jsonify({config.error_msg_key: error_string}), 422


def default_unauthorized_callback(error_string):
Expand All @@ -57,23 +59,23 @@ def default_unauthorized_callback(error_string):

:param error_string: String indicating why this request is unauthorized
"""
return jsonify({'msg': error_string}), 401
return jsonify({config.error_msg_key: error_string}), 401


def default_needs_fresh_token_callback():
"""
By default, if a non-fresh jwt is used to access a ```fresh_jwt_required```
endpoint, we return a general error message with a 401 status code
"""
return jsonify({'msg': 'Fresh token required'}), 401
return jsonify({config.error_msg_key: 'Fresh token required'}), 401


def default_revoked_token_callback():
"""
By default, if a revoked token is used to access a protected endpoint, we
return a general error message with a 401 status code
"""
return jsonify({'msg': 'Token has been revoked'}), 401
return jsonify({config.error_msg_key: 'Token has been revoked'}), 401


def default_user_loader_error_callback(identity):
Expand All @@ -82,7 +84,7 @@ def default_user_loader_error_callback(identity):
function returns None, we return a general error message with a 401
status code
"""
return jsonify({'msg': "Error loading the user {}".format(identity)}), 401
return jsonify({config.error_msg_key: "Error loading the user {}".format(identity)}), 401


def default_claims_verification_callback(user_claims):
Expand All @@ -97,4 +99,4 @@ def default_claims_verification_failed_callback():
By default, if the user claims verification failed, we return a generic
error message with a 400 status code
"""
return jsonify({'msg': 'User claims verification failed'}), 400
return jsonify({config.error_msg_key: 'User claims verification failed'}), 400
2 changes: 2 additions & 0 deletions flask_jwt_extended/jwt_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ def _set_default_configuration_options(app):

app.config.setdefault('JWT_CLAIMS_IN_REFRESH_TOKEN', False)

app.config.setdefault('JWT_ERROR_MESSAGE_KEY', 'msg')

def user_claims_loader(self, callback):
"""
This decorator sets the callback function for adding custom claims to an
Expand Down
6 changes: 6 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ def test_default_configs(app):

assert config.json_encoder is app.json_encoder

assert config.error_msg_key == 'msg'


def test_override_configs(app):
app.config['JWT_TOKEN_LOCATION'] = ['cookies', 'query_string']
Expand Down Expand Up @@ -104,6 +106,8 @@ def test_override_configs(app):

app.config['JWT_CLAIMS_IN_REFRESH_TOKEN'] = True

app.config['JWT_ERROR_MESSAGE_KEY'] = 'message'

class CustomJSONEncoder(JSONEncoder):
pass

Expand Down Expand Up @@ -156,6 +160,8 @@ class CustomJSONEncoder(JSONEncoder):

assert config.json_encoder is CustomJSONEncoder

assert config.error_msg_key == 'message'


def test_tokens_never_expire(app):
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = False
Expand Down
6 changes: 6 additions & 0 deletions tests/test_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,9 @@ def custom_response(err_str):
response = test_client.get('/protected', headers=None)
assert response.status_code == 201
assert response.get_json() == {'foo': "bar"}


def test_custom_error_msg_key(app):
app.config['JWT_ERROR_MESSAGE_KEY'] = 'message'
response = app.test_client().get('/protected', headers=None)
assert response.get_json() == {'message': 'Missing Authorization Header'}