Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
pyramid.pdf
Скачиваний:
10
Добавлен:
24.03.2015
Размер:
3.82 Mб
Скачать

15. SESSIONS

1

2

3

4

5

6

7

8

9

>>>request.session.flash(’info message’)

>>>request.session.peek_flash()

[’info message’]

>>>request.session.peek_flash() [’info message’]

>>>request.session.pop_flash() [’info message’]

>>>request.session.peek_flash()

[]

15.6 Preventing Cross-Site Request Forgery Attacks

Cross-site request forgery attacks are a phenomenon whereby a user with an identity on your website might click on a URL or button on another website which secretly redirects the user to your application to perform some command that requires elevated privileges.

You can avoid most of these attacks by making sure that the correct CSRF token has been set in an Pyramid session object before performing any actions in code which requires elevated privileges that is invoked via a form post. To use CSRF token support, you must enable a session factory as described in Using The Default Session Factory or Using Alternate Session Factories.

15.6.1 Using the session.get_csrf_token Method

To get the current CSRF token from the session, use the session.get_csrf_token() method.

token = request.session.get_csrf_token()

The session.get_csrf_token() method accepts no arguments. It returns a CSRF token string. If session.get_csrf_token() or session.new_csrf_token() was invoked previously for this session, the existing token will be returned. If no CSRF token previously existed for this session, a new token will be will be set into the session and returned. The newly created token will be opaque and randomized.

You can use the returned token as the value of a hidden field in a form that posts to a method that requires elevated privileges. The handler for the form post should use session.get_csrf_token() again to obtain the current CSRF token related to the user from the session, and compare it to the value of the hidden form field. For example, if your form rendering included the CSRF token obtained via session.get_csrf_token() as a hidden input field named csrf_token:

176

15.6. PREVENTING CROSS-SITE REQUEST FORGERY ATTACKS

1

2

3

token = request.session.get_csrf_token() if token != request.POST[’csrf_token’]:

raise ValueError(’CSRF token did not match’)

15.6.2 Using the session.new_csrf_token Method

To explicitly add a new CSRF token to the session, use the session.new_csrf_token() method. This differs only from session.get_csrf_token() inasmuch as it clears any existing CSRF token, creates a new CSRF token, sets the token into the session, and returns the token.

token = request.session.new_csrf_token()

177

15. SESSIONS

178

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]