def authenticate(self, req, resp, resource):
        request_header = self.parse_auth_token_from_request(
            req.get_header('Authorization'))

        try:
            # Validate the Authorization header contents and lookup the user's credentials
            # via the provided `credentials_map` function.
            receiver = mohawk.Receiver(
                credentials_map=partial(self.credentials_map, req, resp,
                                        resource),
                request_header=request_header,
                method=req.method,
                url=req.forwarded_uri,
                content=req.context.get('body'),
                content_type=req.get_header('Content-Type'),
                **self.receiver_kwargs)
        except mohawk.exc.HawkFail as ex:
            raise BackendAuthenticationFailure(
                backend=self,
                description='{0}({1!s})'.format(ex.__class__.__name__, ex),
                challenges=([getattr(ex, 'www_authenticate')] if hasattr(
                    ex, 'www_authenticate') else []))

        # The authentication was successful, return the previously retrieved user now
        return {
            'user': receiver.resource.credentials['user'],
            'receiver': receiver,
        }
Beispiel #2
0
    def authenticate(self, req, resp, resource):
        request_header = self.parse_auth_token_from_request(
            req.get_header('Authorization'))

        try:
            # Validate the Authorization header contents and lookup the user's credentials
            # via the provided `credentials_map` function.
            receiver = mohawk.Receiver(
                request_header=request_header,
                method=req.method,
                url=req.forwarded_uri,
                content=req.context.get('body'),
                content_type=req.get_header('Content-Type'),
                **self.receiver_kwargs)
        except mohawk.exc.HawkFail as ex:
            raise falcon.HTTPUnauthorized(
                description='{0}({1!s})'.format(ex.__class__.__name__, ex),
                challenges=([getattr(ex, 'www_authenticate')] if hasattr(
                    ex, 'www_authenticate') else []))

        # The authentication was successful, get the actual user object now.
        user = self.user_loader(receiver.parsed_header['id'])
        if not user:
            # Should never really happen unless your user objects and their
            # credentials are out of sync.
            raise falcon.HTTPUnauthorized(description='Invalid User')

        return user
Beispiel #3
0
    def _auth_by_signature(self):
        if self._client_key_loader_func is None:
            raise RuntimeError('Client key loader function was not defined')
        if 'Authorization' not in request.headers:
            raise Unauthorized()

        try:
            mohawk.Receiver(credentials_map=self._client_key_loader_func,
                            request_header=request.headers['Authorization'],
                            url=request.url,
                            method=request.method,
                            content=request.get_data(),
                            content_type=request.mimetype,
                            accept_untrusted_content=current_app.
                            config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],
                            localtime_offset_in_seconds=current_app.
                            config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],
                            timestamp_skew_in_seconds=current_app.
                            config['HAWK_TIMESTAMP_SKEW_IN_SECONDS'])
        except mohawk.exc.MacMismatch:
            # mohawk exception contains computed MAC.
            # We should not expose it in response.
            raise Unauthorized()
        except (mohawk.exc.CredentialsLookupError, mohawk.exc.AlreadyProcessed,
                mohawk.exc.MisComputedContentHash,
                mohawk.exc.TokenExpired) as e:
            raise Unauthorized(str(e))
        except mohawk.exc.HawkFail as e:
            raise BadRequest(str(e))
        except KeyError:
            raise BadRequest()
Beispiel #4
0
    def _sign_response(self, response):
        """Signs a response if it's possible."""
        if 'Authorization' not in request.headers:
            return response

        try:
            mohawk_receiver = mohawk.Receiver(
                credentials_map=self._client_key_loader_func,
                request_header=request.headers['Authorization'],
                url=request.url,
                method=request.method,
                content=request.get_data(),
                content_type=request.mimetype,
                accept_untrusted_content=current_app.
                config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],
                localtime_offset_in_seconds=current_app.
                config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],
                timestamp_skew_in_seconds=current_app.
                config['HAWK_TIMESTAMP_SKEW_IN_SECONDS'])
        except mohawk.exc.HawkFail:
            return response

        response.headers['Server-Authorization'] = mohawk_receiver.respond(
            content=response.data, content_type=response.mimetype)
        return response
Beispiel #5
0
 async def raise_if_not_authentic(request):
     mohawk.Receiver(
         lookup_credentials,
         request.headers['Authorization'],
         str(request.url),
         request.method,
         content=await request.content.read(),
         content_type=request.headers['Content-Type'],
         seen_nonce=seen_nonce,
     )
Beispiel #6
0
 def __call__(self, request, context):
     """
     Mock the server authorization response for validating the response content
     """
     response = json.dumps(self._response)
     credentials = (lambda key: self.credentials)
     receiver = mohawk.Receiver(
         credentials,
         request.headers['Authorization'],
         request.url,
         request.method,
         content=request.text,
         content_type=request.headers.get('Content-Type', ''),
     )
     receiver.respond(
         content=response,
         content_type=self.content_type,
     )
     context.headers['Server-Authorization'] = receiver.response_header
     context.headers['Content-Type'] = self.content_type
     return response
    def _auth_by_signature(self):
        if self._client_key_loader_func is None:
            raise RuntimeError('Client key loader function was not defined')
        if 'Authorization' not in request.headers:
            raise Unauthorized()

        try:
            return mohawk.Receiver(
                credentials_map=self._client_key_loader_func,
                seen_nonce=self._nonce_checker_func
                if current_app.config['access_control']['hawk_nonce_enabled']
                else None,
                request_header=request.headers['Authorization'],
                url=request.url,
                method=request.method,
                content=request.get_data(),
                content_type=request.mimetype,
                accept_untrusted_content=current_app.config['access_control']
                ['hawk_accept_untrusted_content'],
                localtime_offset_in_seconds=current_app.
                config['access_control']['hawk_localtime_offset_in_seconds'],
                timestamp_skew_in_seconds=current_app.config['access_control']
                ['hawk_timestamp_skew_in_seconds'],
            )
        except mohawk.exc.MacMismatch:
            raise Unauthorized()
        except (
                mohawk.exc.CredentialsLookupError,
                mohawk.exc.AlreadyProcessed,
                mohawk.exc.MisComputedContentHash,
                mohawk.exc.TokenExpired,
        ) as e:
            raise Unauthorized(str(e))
        except mohawk.exc.HawkFail as e:
            raise BadRequest(str(e))
        except KeyError:
            raise BadRequest()