|
4 | 4 | from flask_jwt_extended import (
|
5 | 5 | jwt_required, JWTManager, jwt_refresh_token_required, create_access_token,
|
6 | 6 | create_refresh_token, set_access_cookies, set_refresh_cookies,
|
7 |
| - unset_jwt_cookies |
| 7 | + unset_jwt_cookies, jwt_optional |
8 | 8 | )
|
9 | 9 |
|
10 | 10 | def _get_cookie_from_response(response, cookie_name):
|
@@ -66,6 +66,11 @@ def refresh_protected():
|
66 | 66 | def post_refresh_protected():
|
67 | 67 | return jsonify(foo='bar')
|
68 | 68 |
|
| 69 | + @app.route('/optional_post_protected', methods=['POST']) |
| 70 | + @jwt_optional |
| 71 | + def optional_post_protected(): |
| 72 | + return jsonify(foo='bar') |
| 73 | + |
69 | 74 | return app
|
70 | 75 |
|
71 | 76 |
|
@@ -391,3 +396,21 @@ def test_cookies_without_csrf(app):
|
391 | 396 | assert len(cookies) == 1
|
392 | 397 | refresh_cookie = _get_cookie_from_response(response, 'refresh_token_cookie')
|
393 | 398 | assert refresh_cookie is not None
|
| 399 | + |
| 400 | +def test_jwt_optional_with_csrf_enabled(app): |
| 401 | + test_client = app.test_client() |
| 402 | + |
| 403 | + # User without a token should be able to reach the endpoint without |
| 404 | + # getting a CSRF error |
| 405 | + response = test_client.post('/optional_post_protected') |
| 406 | + json_data = json.loads(response.get_data(as_text=True)) |
| 407 | + assert response.status_code == 200 |
| 408 | + assert json_data == {'foo': 'bar'} |
| 409 | + |
| 410 | + # User with a token should still get a CSRF error if csrf not present |
| 411 | + response = test_client.get('/access_token') |
| 412 | + csrf_token = _get_cookie_from_response(response, 'csrf_access_token')['csrf_access_token'] |
| 413 | + response = test_client.post('/optional_post_protected') |
| 414 | + json_data = json.loads(response.get_data(as_text=True)) |
| 415 | + assert response.status_code == 401 |
| 416 | + assert json_data == {'msg': 'Missing CSRF token in headers'} |
0 commit comments