def test_server_api_with_abs_url(self):
        url = 'http://someserver/bazz?buzz=fizz&mode=ala'

        req = {
            'method': 'GET',
            'url': url,
            'host': 'example.com',
            'port': 80,
            'headers': {
                'authorization':
                'Hawk id="foobar-1234", ts="1367927332", nonce="lwfuar", ext="and welcome!", mac="ZZI/y3M0gV7PWCRX1VddptkWhunWxrpQikXAsLYzblU="'
            }
        }
        server = hawk.Server(req, lambda cid: CREDS[cid])
        artifacts = server.authenticate(
            {'timestampSkewSec': self._skewed_now()})

        self.assertEqual(artifacts['resource'], '/bazz?buzz=fizz&mode=ala')

        payload = 'Hello and welcome!'
        header = server.header(artifacts, {
            'payload': payload,
            'contentType': 'text/plain'
        })

        assert header == 'Hawk mac="okjCR+o26FMhInYoJ1QO30Fu9cl3wGIWmwqydQXND+w=", hash="y+iZjG+hr2is3SmZLFOe551/LGS3PQPMY9ZWjToaNjg=", ext="and welcome!"'
コード例 #2
0
    def process_request(self, request):
        if "HTTP_AUTHORIZATION" in request.META:
            if request.META["HTTP_AUTHORIZATION"].startswith('Hawk '):
                try:
                    req = self.get_request_dict(request)

                    artifacts = hawk.Server(
                        req=req, credentials_fn=self.get_credentials_lookup(
                        )).authenticate(
                            req,
                            {
                                #'payload': req.DATA #TODO
                            })

                    if False:  #if timestamp out of time
                        pass
                        # TODO
                        # return Response with current timestemp for sync

                    api_user_id = artifacts['id']

                    api_user = get_access_key_model().objects.get(
                        id=api_user_id)
                    api_user.set_artifacts(artifacts)

                    request.api_user = api_user
                except hawk.util.HawkException, e:
                    return get_HawkExceptions_Response(request, e)
                    raise  #return None # TODO raise Exception?
                except ApiKeyNeedsRevalidation, e:
                    return get_RevalidationException_Response(request, e)
                except InvalidKey, e:
                    return get_InvalidKeyException_Response(request, e)
コード例 #3
0
    def verify_auth_header(self, method, url, data, header):
        logging.debug("verify_auth_header()")

        parsed_url = parse_normalized_url(url)

        req = {
            'method': method,
            'url': url,
            'host': parsed_url['hostname'],
            'port': parsed_url['port'],
            'headers': {
                'authorization': header
            }
        }

        logging.debug("hawk auth request:\n" + pprint.pformat(req))

        credentials = {
            self.id.replace('=', ''): {
                'id': self.id,
                'key': self.key,
                'algorithm': 'sha256',
            }
        }

        logging.debug("hawk auth credentials:\n" + pprint.pformat(credentials))

        server = hawk.Server(req, lambda cid: credentials[cid])

        # This will raise a hawk.util.HawkException if it fails
        artifacts = server.authenticate({})

        #logging.debug("hawk auth artifacts:\n" + pprint.pformat(artifacts))

        return True
    def test_bewit(self):
        bewit = hawk.client.get_bewit(url, {
            'credentials': CREDS['foobar-1234'],
            'ttl_sec': 60 * 1000
        })
        req = {
            'method': 'GET',
            'url': '/bazz?buzz=fizz&mode=ala&bewit=' + bewit,
            'host': 'example.com',
            'port': 80,
            'headers': {}
        }

        server = hawk.Server(req, lambda cid: CREDS[cid])
        assert server.authenticate_bewit({})
    def test_parsing_empty_attrs(self):
        url = '/bazz?buzz=fizz&mode=ala'

        req = {
            'method': 'GET',
            'url': url,
            'host': 'example.com',
            'port': 80,
            'headers': {
                'authorization':
                'Hawk id="foobar-1234", app="", ts="1367927332", nonce="lwfuar", ext="and welcome!", mac="ZZI/y3M0gV7PWCRX1VddptkWhunWxrpQikXAsLYzblU="'
            }
        }
        server = hawk.Server(req, lambda cid: CREDS[cid])
        artifacts = server.authenticate(
            {'timestampSkewSec': self._skewed_now()})
コード例 #6
0
    def simple_app(environ, start_response):
        """
        Usage: python test_server.py

        Then in compatibility/nodejs/ run
        node client.js

        This will make an unauthorized and then a HAWK authorized
        request. The authed one should say (valid).
        """
        setup_testing_defaults(environ)

        # TODO no querysting, don't append
        url = environ['PATH_INFO'] + '?' + environ['QUERY_STRING']

        http_auth_header = ''
        if 'HTTP_AUTHORIZATION' in environ:
            http_auth_header = environ['HTTP_AUTHORIZATION']

        # TODO do host and port better
        req = {
            'method': environ['REQUEST_METHOD'],
            'url': url,
            'host': environ['HTTP_HOST'].split(':')[0],
            'port': environ['HTTP_HOST'].split(':')[1],
            'headers': {
                'authorization': http_auth_header
            }
        }

        # Look up from DB or elsewhere
        credentials = {
            'dh37fgj492je': {
                'id': 'dh37fgj492je',
                'algorithm': 'sha256',
                'key': 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn'
            }
        }

        server = hawk.Server(req, lambda cid: credentials[cid])

        if url.find('bewit=') == -1:
            print("HAWK based authentication")
            return hawk_authentication(start_response, server)
        else:
            print("Bewit based authentication")
            return hawk_bewit_authentication(start_response, server)
コード例 #7
0
    def process_response(self, request, response):
        if response.status_code == 500:
            return response
        if hasattr(request, "api_user"):
            req = self.get_request_dict(request)
            header = hawk.Server(
                req=req, credentials_fn=self.get_credentials_lookup()).header(
                    artifacts=request.api_user.get_artifacts(),
                    options={
                        'payload': response.content,
                        'contentType': response['Content-Type']
                    })

            if header:
                response['Server-Authorization'] = header

        return response