Exemple #1
0
    async def endpoint_wrapper(request, *args, **kwargs):
        if not request.method in SUBMIT_METHODS:
            return await func(request, *args, **kwargs)
        
        # get token
        signed_token = await get_csrf_token(request)

        config = request.state.csrf_config
        
        # validate token
        try:
            validate_csrf(request,
                          signed_token,
                          secret_key=config['csrf_secret'],
                          field_name=config['csrf_field_name'],
                          time_limit=config['csrf_time_limit'])
        except ValidationError as e:
            raise CSRFError(e.args[0])

        # strict ssl check
        if request.url.scheme == 'https' and config['csrf_ssl_strict']:
            referrer = request.headers.get('REFERER')

            if not referrer:
                raise CSRFError('The referrer header is missing.')

            if not same_origin(urlparse(referrer), request.url):
                raise CSRFError('The referrer does not match the host.')
        
        # mark request as valid
        request.state.csrf_valid = True

        # pass on request
        return await func(request, *args, **kwargs)
Exemple #2
0
    async def validate(request):
        signed_token = request.query_params['csrf_token']

        try:
            validate_csrf(request, signed_token, **kwargs)
        except ValidationError:
            return PlainTextResponse('False')

        return PlainTextResponse('True')
Exemple #3
0
    async def index(request):
        kwargs = {'secret_key': Secret('yyy'), 'field_name': 'csrf_token'}

        # generate token
        signed_token = generate_csrf(request, **kwargs)

        # test valid data
        validate_csrf(request, signed_token, **kwargs)

        return PlainTextResponse()
Exemple #4
0
    def validate_csrf_token(self, form, field):
        meta = self.form_meta

        if hasattr(meta.csrf_context.state, 'csrf_valid'):
            # already validated by CSRFProtectMiddleware
            return

        validate_csrf(
            request=meta.csrf_context,
            data=field.data,
            secret_key=meta.csrf_secret,
            field_name=meta.csrf_field_name,
            time_limit=meta.csrf_time_limit)
Exemple #5
0
    async def index(request):
        kwargs = {'secret_key': 'yyy', 'field_name': 'csrf_token'}

        # generate token
        signed_token = generate_csrf(request, **kwargs)

        # test valid data
        validate_csrf(request, signed_token, **kwargs)

        # test expired data
        with pytest.raises(ValidationError) as excinfo:
            validate_csrf(request, signed_token, time_limit=-1, **kwargs)

        assert str(excinfo.value) == 'The CSRF token has expired.'

        return PlainTextResponse()