Hi,

I'm using Pyramid 1.84 and trying to implement a CSRF token cookie
verification for any POST or AJAX request.
My code is as follow:


    CSRF_TOKEN_COOKIE_NAME = 'csrf_token'

    @subscriber(INewRequest)
    def handle_new_request(event):
        """Handle any request with CSRF token cookie"""
        request = event.request
        if (request.method == 'POST') or request.is_xhr:
            check_csrf_origin(request)
            post_token = request.cookies.get(CSRF_TOKEN_COOKIE_NAME)
            session_token = request.session.get_csrf_token()
            if (not post_token) or strings_differ(post_token, session_token):
                raise BadCSRFToken('Invalid CSRF token')

    @subscriber(INewResponse)
    def handle_new_response(event):
        """Handle new response to manage CSRF token cookie"""
        request = event.request
        if not request.path.startswith('/--static--/'):
            token = request.session.get_csrf_token()
            event.response.set_cookie(CSRF_TOKEN_COOKIE_NAME, token,
                                      secure=request.scheme == 'https',
                                      httponly=True)


Everything seems to be OK, except on one point : on first submit (which
generally comes from the login page), the CSRF token is refused! On second
submit and afterwards, everything is OK!

Any idea about how to avoid this?

Best regards,
Thierry

-- 
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/pylons-discuss/CAPX_VWCf7u_bsreg7Z-1U6RSjcEH_8TV5auOM9Bsk0_fyP-Ajw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to