Skip to content

Commit

Permalink
cache CSRF token per request, not per app context
Browse files Browse the repository at this point in the history
signed token is available as request.csrf_token
raw token is available as session['csrf_token']
closes #227
  • Loading branch information
davidism committed Oct 23, 2016
1 parent a7b5d00 commit a8d8089
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions flask_wtf/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from functools import wraps

from flask import Blueprint, current_app, request, session
from flask import g
from itsdangerous import BadData, URLSafeTimedSerializer
from werkzeug.exceptions import BadRequest
from werkzeug.security import safe_str_cmp
Expand All @@ -40,14 +39,14 @@ def generate_csrf(secret_key=None, token_key='csrf_token'):
:param secret_key: A secret key for mixing in the token, default is ``Flask.secret_key``.
"""

if token_key not in g:
if not hasattr(request, 'csrf_token'):
if token_key not in session:
session[token_key] = hashlib.sha1(os.urandom(64)).hexdigest()

s = URLSafeTimedSerializer(_get_secret_key(secret_key), salt='wtf-csrf-token')
setattr(g, token_key, s.dumps(session[token_key]))
request.csrf_token = s.dumps(session[token_key])

return getattr(g, token_key)
return request.csrf_token


def validate_csrf(data, secret_key=None, time_limit=None, token_key='csrf_token'):
Expand Down

0 comments on commit a8d8089

Please sign in to comment.