Skip to content

Commit e60ee53

Browse files
committed
Logout example in docs when using cookies (refs #12)
1 parent 9b5401a commit e60ee53

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

examples/csrf_protection_with_cookies.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from flask_jwt_extended import JWTManager, jwt_required, \
44
create_access_token, jwt_refresh_token_required, \
55
create_refresh_token, get_jwt_identity, set_access_cookies, \
6-
set_refresh_cookies
7-
6+
set_refresh_cookies, unset_jwt_cookies
87

98
app = Flask(__name__)
109
app.secret_key = 'super-secret' # Change this!
@@ -73,6 +72,19 @@ def refresh():
7372
return resp, 200
7473

7574

75+
# Because the JWTs are stored in an httponly cookie now, we cannot
76+
# log the user out by simply deleting the cookie in the frontend.
77+
# We need the backend to send us a response to delete the cookies
78+
# in order to logout. unset_jwt_cookies is a helper function to
79+
# do just that.
80+
@app.route('/token/remove', methods=['POST'])
81+
@jwt_required
82+
def logout():
83+
resp = jsonify({'logout': True})
84+
unset_jwt_cookies(resp)
85+
return resp, 200
86+
87+
7688
@app.route('/api/example', methods=['GET'])
7789
@jwt_required
7890
def protected():

examples/jwt_in_cookie.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from flask_jwt_extended import JWTManager, jwt_required, \
44
create_access_token, jwt_refresh_token_required, \
55
create_refresh_token, get_jwt_identity, set_access_cookies, \
6-
set_refresh_cookies
6+
set_refresh_cookies, unset_jwt_cookies
77

88
# NOTE: This is just a basic example of how to enable cookies. This is
99
# vulnerable to CSRF attacks, and should not be used as is. See
@@ -66,6 +66,19 @@ def refresh():
6666
return resp, 200
6767

6868

69+
# Because the JWTs are stored in an httponly cookie now, we cannot
70+
# log the user out by simply deleting the cookie in the frontend.
71+
# We need the backend to send us a response to delete the cookies
72+
# in order to logout. unset_jwt_cookies is a helper function to
73+
# do just that.
74+
@app.route('/token/remove', methods=['POST'])
75+
@jwt_required
76+
def logout():
77+
resp = jsonify({'logout': True})
78+
unset_jwt_cookies(resp)
79+
return resp, 200
80+
81+
6982
# We do not need to make any changes to our protected endpoints. They
7083
# will all still function the exact same as they do when sending the
7184
# JWT in via a header instead of a cookie

0 commit comments

Comments
 (0)