Python django.conf.settings.CSRF_COOKIE_NAME Examples
The following are 30
code examples of django.conf.settings.CSRF_COOKIE_NAME().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.conf.settings
, or try the search function
.
Example #1
Source File: middleware.py From django-cookies-samesite with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, *args, **kwargs): self.protected_cookies = get_config_setting( "SESSION_COOKIE_SAMESITE_KEYS", set() ) if not isinstance(self.protected_cookies, (list, set, tuple)): raise ValueError( "SESSION_COOKIE_SAMESITE_KEYS should be a list, set or tuple." ) self.protected_cookies = set(self.protected_cookies) self.protected_cookies |= { settings.SESSION_COOKIE_NAME, settings.CSRF_COOKIE_NAME, } samesite_flag = get_config_setting("SESSION_COOKIE_SAMESITE", "") self.samesite_flag = ( str(samesite_flag).capitalize() if samesite_flag is not None else "" ) self.samesite_force_all = get_config_setting( "SESSION_COOKIE_SAMESITE_FORCE_ALL" ) return super(CookiesSameSite, self).__init__(*args, **kwargs)
Example #2
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_process_response_get_token_not_used(self): """ If get_token() is not called, the view middleware does not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_GET_no_csrf_cookie_request() # non_token_view_using_request_processor does not call get_token(), but # does use the csrf request processor. By using this, we are testing # that the view processor is properly lazy and doesn't call get_token() # until needed. self.mw.process_request(req) self.mw.process_view(req, non_token_view_using_request_processor, (), {}) resp = non_token_view_using_request_processor(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertIs(csrf_cookie, False) # Check the request processing
Example #3
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_csrf_cookie_age_none(self): """ CSRF cookie age does not have max age set and therefore uses session-based cookies. """ req = self._get_GET_no_csrf_cookie_request() MAX_AGE = None with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_DOMAIN='.example.com', CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH='/test/', CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True): # token_view calls get_token() indirectly self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) max_age = resp2.cookies.get('csrfcookie').get('max-age') self.assertEqual(max_age, '')
Example #4
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_csrf_cookie_age(self): """ CSRF cookie age can be set using settings.CSRF_COOKIE_AGE. """ req = self._get_GET_no_csrf_cookie_request() MAX_AGE = 123 with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_DOMAIN='.example.com', CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH='/test/', CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True): # token_view calls get_token() indirectly self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) max_age = resp2.cookies.get('csrfcookie').get('max-age') self.assertEqual(max_age, MAX_AGE)
Example #5
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_cookie_not_reset_on_accepted_request(self): """ The csrf token used in posts is changed on every request (although stays equivalent). The csrf cookie should not change on accepted requests. If it appears in the response, it should keep its value. """ req = self._get_POST_request_with_token() self.mw.process_request(req) self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp = self.mw.process_response(req, resp) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) if csrf_cookie: self.assertEqual( csrf_cookie.value, self._csrf_id_cookie, "CSRF cookie was changed on an accepted request" )
Example #6
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_cookie_not_reset_on_accepted_request(self): """ The csrf token used in posts is changed on every request (although stays equivalent). The csrf cookie should not change on accepted requests. If it appears in the response, it should keep its value. """ req = self._get_POST_request_with_token() self.mw.process_request(req) self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp = self.mw.process_response(req, resp) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) if csrf_cookie: self.assertEqual( csrf_cookie.value, self._csrf_id_cookie, "CSRF cookie was changed on an accepted request" )
Example #7
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_csrf_cookie_age(self): """ CSRF cookie age can be set using settings.CSRF_COOKIE_AGE. """ req = self._get_GET_no_csrf_cookie_request() MAX_AGE = 123 with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_DOMAIN='.example.com', CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH='/test/', CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True): # token_view calls get_token() indirectly self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) max_age = resp2.cookies.get('csrfcookie').get('max-age') self.assertEqual(max_age, MAX_AGE)
Example #8
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_process_response_get_token_not_used(self): """ If get_token() is not called, the view middleware does not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_GET_no_csrf_cookie_request() # non_token_view_using_request_processor does not call get_token(), but # does use the csrf request processor. By using this, we are testing # that the view processor is properly lazy and doesn't call get_token() # until needed. self.mw.process_request(req) self.mw.process_view(req, non_token_view_using_request_processor, (), {}) resp = non_token_view_using_request_processor(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertIs(csrf_cookie, False) # Check the request processing
Example #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_csrf_cookie_age_none(self): """ CSRF cookie age does not have max age set and therefore uses session-based cookies. """ req = self._get_GET_no_csrf_cookie_request() MAX_AGE = None with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_DOMAIN='.example.com', CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH='/test/', CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True): # token_view calls get_token() indirectly self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) max_age = resp2.cookies.get('csrfcookie').get('max-age') self.assertEqual(max_age, '')
Example #10
Source File: csrf.py From python2017 with MIT License | 6 votes |
def _get_token(self, request): if settings.CSRF_USE_SESSIONS: try: return request.session.get(CSRF_SESSION_KEY) except AttributeError: raise ImproperlyConfigured( 'CSRF_USE_SESSIONS is enabled, but request.session is not ' 'set. SessionMiddleware must appear before CsrfViewMiddleware ' 'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '') ) else: try: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] except KeyError: return None csrf_token = _sanitize_token(cookie_token) if csrf_token != cookie_token: # Cookie token needed to be replaced; # the cookie needs to be reset. request.csrf_cookie_needs_reset = True return csrf_token
Example #11
Source File: csrf.py From openhgsenti with Apache License 2.0 | 6 votes |
def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age=settings.CSRF_COOKIE_AGE, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, httponly=settings.CSRF_COOKIE_HTTPONLY ) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response
Example #12
Source File: csrf.py From python with Apache License 2.0 | 6 votes |
def _get_token(self, request): if settings.CSRF_USE_SESSIONS: try: return request.session.get(CSRF_SESSION_KEY) except AttributeError: raise ImproperlyConfigured( 'CSRF_USE_SESSIONS is enabled, but request.session is not ' 'set. SessionMiddleware must appear before CsrfViewMiddleware ' 'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '') ) else: try: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] except KeyError: return None csrf_token = _sanitize_token(cookie_token) if csrf_token != cookie_token: # Cookie token needed to be replaced; # the cookie needs to be reset. request.csrf_cookie_needs_reset = True return csrf_token
Example #13
Source File: csrf.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _set_token(self, request, response): if settings.CSRF_USE_SESSIONS: request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE'] else: response.set_cookie( settings.CSRF_COOKIE_NAME, request.META['CSRF_COOKIE'], max_age=settings.CSRF_COOKIE_AGE, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, httponly=settings.CSRF_COOKIE_HTTPONLY, samesite=settings.CSRF_COOKIE_SAMESITE, ) # Set the Vary header since content varies with the CSRF cookie. patch_vary_headers(response, ('Cookie',))
Example #14
Source File: csrf.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _get_token(self, request): if settings.CSRF_USE_SESSIONS: try: return request.session.get(CSRF_SESSION_KEY) except AttributeError: raise ImproperlyConfigured( 'CSRF_USE_SESSIONS is enabled, but request.session is not ' 'set. SessionMiddleware must appear before CsrfViewMiddleware ' 'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '') ) else: try: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] except KeyError: return None csrf_token = _sanitize_token(cookie_token) if csrf_token != cookie_token: # Cookie token needed to be replaced; # the cookie needs to be reset. request.csrf_cookie_needs_reset = True return csrf_token
Example #15
Source File: csrf.py From bioforum with MIT License | 6 votes |
def _get_token(self, request): if settings.CSRF_USE_SESSIONS: try: return request.session.get(CSRF_SESSION_KEY) except AttributeError: raise ImproperlyConfigured( 'CSRF_USE_SESSIONS is enabled, but request.session is not ' 'set. SessionMiddleware must appear before CsrfViewMiddleware ' 'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '') ) else: try: cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] except KeyError: return None csrf_token = _sanitize_token(cookie_token) if csrf_token != cookie_token: # Cookie token needed to be replaced; # the cookie needs to be reset. request.csrf_cookie_needs_reset = True return csrf_token
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_csrf_cookie_samesite(self): req = self._get_GET_no_csrf_cookie_request() with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_SAMESITE='Strict'): self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) self.assertEqual(resp2.cookies['csrfcookie']['samesite'], 'Strict')
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_process_view_token_too_long(self): """ If the token is longer than expected, it is ignored and a new token is created. """ req = self._get_GET_no_csrf_cookie_request() req.COOKIES[settings.CSRF_COOKIE_NAME] = 'x' * 100000 self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
Example #18
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_bare_secret_accepted_and_replaced(self): """ The csrf token is reset from a bare secret. """ req = self._get_POST_bare_secret_csrf_cookie_request_with_token() self.mw.process_request(req) req2 = self.mw.process_view(req, token_view, (), {}) self.assertIsNone(req2) resp = token_view(req) resp = self.mw.process_response(req, resp) self.assertIn(settings.CSRF_COOKIE_NAME, resp.cookies, "Cookie was not reset from bare secret") csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME] self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value)
Example #19
Source File: test_views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_login_csrf_rotate(self): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # The test client isn't used here as it's a test for middleware. req = HttpRequest() CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = LoginView.as_view()(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = {'username': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = LoginView.as_view()(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2)
Example #20
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_ensures_csrf_cookie_with_middleware(self): """ The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware enabled. """ req = self._get_GET_no_csrf_cookie_request() self.mw.process_view(req, ensure_csrf_cookie_view, (), {}) resp = ensure_csrf_cookie_view(req) resp2 = self.mw.process_response(req, resp) self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)) self.assertIn('Cookie', resp2.get('Vary', ''))
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def _get_POST_bare_secret_csrf_cookie_request(self): req = self._get_POST_no_csrf_cookie_request() req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie[:32] return req
Example #22
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def _get_GET_csrf_cookie_request(self): req = TestingHttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie return req
Example #23
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_token_node_with_new_csrf_cookie(self): """ CsrfTokenNode works when a CSRF cookie is created by the middleware (when one was not already present) """ req = self._get_GET_no_csrf_cookie_request() self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies[settings.CSRF_COOKIE_NAME] self._check_token_present(resp, csrf_id=csrf_cookie.value)
Example #24
Source File: csrf.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def process_response(self, request, response): if getattr(response, 'csrf_processing_done', False): return response # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was # never called, probably because a request middleware returned a response # (for example, contrib.auth redirecting to a login page). if request.META.get("CSRF_COOKIE") is None: return response if not request.META.get("CSRF_COOKIE_USED", False): return response # Set the CSRF cookie even if it's already set, so we renew # the expiry timer. response.set_cookie(settings.CSRF_COOKIE_NAME, request.META["CSRF_COOKIE"], max_age=settings.CSRF_COOKIE_AGE, domain=settings.CSRF_COOKIE_DOMAIN, path=settings.CSRF_COOKIE_PATH, secure=settings.CSRF_COOKIE_SECURE, httponly=settings.CSRF_COOKIE_HTTPONLY ) # Content varies with the CSRF cookie, so set the Vary header. patch_vary_headers(response, ('Cookie',)) response.csrf_processing_done = True return response
Example #25
Source File: test_account.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_returns_csrf(self): # Force the client to test for CSRF because the view should be CSRF # exempt. If not exempt then the `client.post` would fail. self.client.handler.enforce_csrf_checks = True self.client.login(user=factory.make_User()) response = self.client.post(reverse("csrf")) self.assertThat(response, HasStatusCode(HTTPStatus.OK)) body = json_load_bytes(response.content) self.assertTrue("csrf" in body) # Should not have an updated CSRF cookie, because it was marked as # not used. self.assertIsNone(response.cookies.get(settings.CSRF_COOKIE_NAME))
Example #26
Source File: test_views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_login_csrf_rotate(self): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # The test client isn't used here as it's a test for middleware. req = HttpRequest() CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = LoginView.as_view()(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = {'username': 'testclient', 'password': 'password', 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, LoginView.as_view(), (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = LoginView.as_view()(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2)
Example #27
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_bare_secret_accepted_and_replaced(self): """ The csrf token is reset from a bare secret. """ req = self._get_POST_bare_secret_csrf_cookie_request_with_token() self.mw.process_request(req) req2 = self.mw.process_view(req, token_view, (), {}) self.assertIsNone(req2) resp = token_view(req) resp = self.mw.process_response(req, resp) self.assertIn(settings.CSRF_COOKIE_NAME, resp.cookies, "Cookie was not reset from bare secret") csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME] self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self._check_token_present(resp, csrf_id=csrf_cookie.value)
Example #28
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_process_view_token_invalid_chars(self): """ If the token contains non-alphanumeric characters, it is ignored and a new token is created. """ token = ('!@#' + self._csrf_id)[:CSRF_TOKEN_LENGTH] req = self._get_GET_no_csrf_cookie_request() req.COOKIES[settings.CSRF_COOKIE_NAME] = token self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH) self.assertNotEqual(csrf_cookie.value, token)
Example #29
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_process_view_token_too_long(self): """ If the token is longer than expected, it is ignored and a new token is created. """ req = self._get_GET_no_csrf_cookie_request() req.COOKIES[settings.CSRF_COOKIE_NAME] = 'x' * 100000 self.mw.process_view(req, token_view, (), {}) resp = token_view(req) resp2 = self.mw.process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) self.assertEqual(len(csrf_cookie.value), CSRF_TOKEN_LENGTH)
Example #30
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_ensures_csrf_cookie_with_middleware(self): """ The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware enabled. """ req = self._get_GET_no_csrf_cookie_request() self.mw.process_view(req, ensure_csrf_cookie_view, (), {}) resp = ensure_csrf_cookie_view(req) resp2 = self.mw.process_response(req, resp) self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)) self.assertIn('Cookie', resp2.get('Vary', ''))