Python requests_kerberos.HTTPKerberosAuth() Examples

The following are 24 code examples of requests_kerberos.HTTPKerberosAuth(). 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 requests_kerberos , or try the search function .
Example #1
Source File: HTTP.py    From watchdog with Apache License 2.0 7 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example #2
Source File: HTTP.py    From watchdog with Apache License 2.0 7 votes vote down vote up
def setAuthMethod(self, auth_method):
        "Set the authentication method to use for the requests."
        self.auth_method = auth_method
        if len(self.auth_credentials) == 2:
            username, password = self.auth_credentials
            if self.auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self.h.auth = HTTPBasicAuth(username, password)
            elif self.auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self.h.auth = HTTPDigestAuth(username, password)
            elif self.auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self.h.auth = HttpNtlmAuth(username, password)
        elif self.auth_method == "kerberos":
            from requests_kerberos import HTTPKerberosAuth
            self.h.auth = HTTPKerberosAuth() 
Example #3
Source File: test_http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_config_kerberos_legacy_remap(self):
        instance = {'auth_type': 'kerberos', 'kerberos': True}
        init_config = {}

        # Trigger lazy import
        http = RequestsWrapper(instance, init_config)
        assert isinstance(http.options['auth'], requests_kerberos.HTTPKerberosAuth)

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper(instance, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.REQUIRED,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            ) 
Example #4
Source File: test_http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_config_kerberos_shortcut(self):
        instance = {'auth_type': 'kerberos', 'kerberos_auth': True}
        init_config = {}

        # Trigger lazy import
        http = RequestsWrapper(instance, init_config)
        assert isinstance(http.options['auth'], requests_kerberos.HTTPKerberosAuth)

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper(instance, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.REQUIRED,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            ) 
Example #5
Source File: test_http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_config_kerberos_legacy(self):
        instance = {'kerberos_auth': 'required'}
        init_config = {}

        # Trigger lazy import
        http = RequestsWrapper(instance, init_config)
        assert isinstance(http.options['auth'], requests_kerberos.HTTPKerberosAuth)

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper(instance, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.REQUIRED,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            ) 
Example #6
Source File: oozie_helper.py    From ibis with Apache License 2.0 6 votes vote down vote up
def put_request(self, suffix_url, xml_file):
        """Make a oozie put request"""
        status = False
        file_h = open(os.path.join(self.cfg_mgr.saves, xml_file))
        data = file_h.read()
        http_headers = {'Content-Type': 'application/xml'}
        url = self.oozie_url + suffix_url
        self.logger.info(url)
        response = requests.post(url, data=data, headers=http_headers,
                                 auth=HTTPKerberosAuth())
        if 200 <= response.status_code and response.status_code < 300:
            my_json = json.dumps(response.json())
            res_val = response.json()
            # self.logger.info(json.dumps(response.json(),
            # indent=4, sort_keys=True))
            msg = "\n\n\t\tGo here: https://{0}:8888/oozie/" \
                  "list_oozie_workflow/{1}/\n".\
                format(self.cfg_mgr.workflow_host, res_val['id'])
            self.logger.info(msg)
            status = True
        else:
            self.logger.error("Error submitting job. Error code: "
                              "{status}".format(status=response.status_code))
            self.logger.error(response.text)
        return status 
Example #7
Source File: oozie_ws_helper.py    From ibis with Apache License 2.0 6 votes vote down vote up
def get_job(self, id_val):
        """Retrieve job with provided id
        :param id_val:String
        :return workflow_job:Workflow"""
        workflow_job = None
        query = 'job/' + id_val
        req_get = requests.get(self.oozie_url + query, auth=HTTPKerberosAuth())
        if req_get.status_code == 200:
            my_json = json.dumps(req_get.json())
            print 'JSON: ', my_json
            workflow_job = Workflow(my_json)
        else:
            err_msg = "Error retrieving job, {id_val}. Error code: {status}"
            err_msg = err_msg.format(id_val=id_val, status=req_get.status_code)
            print err_msg
        return req_get.status_code, workflow_job 
Example #8
Source File: tar.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def _download(url, temp):
    """Downloads the image."""
    _LOGGER.debug('Downloading tar file from %r to %r.', url, temp)

    krb_auth = requests_kerberos.HTTPKerberosAuth(
        mutual_authentication=requests_kerberos.DISABLED,
        # kerberos 1.2.5 doesn't accept None principal. Remove this once fixed.
        principal=''
    )

    request = requests.get(url, stream=True, auth=krb_auth)
    shutil.copyfileobj(request.raw, temp) 
Example #9
Source File: auth.py    From presto-python-client with Apache License 2.0 6 votes vote down vote up
def set_http_session(self, http_session):
        try:
            import requests_kerberos
        except ImportError:
            raise RuntimeError("unable to import requests_kerberos")

        if self._config:
            os.environ["KRB5_CONFIG"] = self._config
        http_session.trust_env = False
        http_session.auth = requests_kerberos.HTTPKerberosAuth(
            mutual_authentication=self._mutual_authentication,
            force_preemptive=self._force_preemptive,
            hostname_override=self._hostname_override,
            sanitize_mutual_error_response=self._sanitize_mutual_error_response,
            principal=self._principal,
            delegate=self._delegate,
            service=self._service_name,
        )
        if self._ca_bundle:
            http_session.verify = self._ca_bundle
        return http_session 
Example #10
Source File: authentication.py    From msrest-for-python with MIT License 6 votes vote down vote up
def signed_session(self, session=None):
        """Create requests session with Negotiate (SPNEGO) headers applied.

        If a session object is provided, configure it directly. Otherwise,
        create a new session and return it.

        :param session: The session to configure for authentication
        :type session: requests.Session
        :rtype: requests.Session
        """
        session = super(KerberosAuthentication, self).signed_session(session)
        try:
            from requests_kerberos import HTTPKerberosAuth
        except ImportError:
            raise ImportError("In order to use KerberosAuthentication please do 'pip install requests_kerberos' first")
        if self.mutual_authentication:
            session.auth = HTTPKerberosAuth(mutual_authentication=self.mutual_authentication)
        else:
            session.auth = HTTPKerberosAuth()
        return session 
Example #11
Source File: crawler.py    From ITWSV with MIT License 6 votes vote down vote up
def auth_method(self, value):
        """Set the authentication method to use for the requests."""
        self._auth_method = value
        if len(self._auth_credentials) == 2:
            username, password = self._auth_credentials
            if self._auth_method == "basic":
                from requests.auth import HTTPBasicAuth
                self._session.auth = HTTPBasicAuth(username, password)
            elif self._auth_method == "digest":
                from requests.auth import HTTPDigestAuth
                self._session.auth = HTTPDigestAuth(username, password)
            elif self._auth_method == "ntlm":
                from requests_ntlm import HttpNtlmAuth
                self._session.auth = HttpNtlmAuth(username, password)
        elif self._auth_method == "kerberos":
            # On openSUSE, "zypper in krb5-devel" before installing the pip package
            from requests_kerberos import HTTPKerberosAuth
            self._session.auth = HTTPKerberosAuth() 
Example #12
Source File: client.py    From jira with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _create_kerberos_session(self, timeout, kerberos_options=None):
        verify = self._options["verify"]
        if kerberos_options is None:
            kerberos_options = {}

        from requests_kerberos import DISABLED
        from requests_kerberos import HTTPKerberosAuth
        from requests_kerberos import OPTIONAL

        if kerberos_options.get("mutual_authentication", "OPTIONAL") == "OPTIONAL":
            mutual_authentication = OPTIONAL
        elif kerberos_options.get("mutual_authentication") == "DISABLED":
            mutual_authentication = DISABLED
        else:
            raise ValueError(
                "Unknown value for mutual_authentication: %s"
                % kerberos_options["mutual_authentication"]
            )

        self._session = ResilientSession(timeout=timeout)
        self._session.verify = verify
        self._session.auth = HTTPKerberosAuth(
            mutual_authentication=mutual_authentication
        ) 
Example #13
Source File: auth.py    From presto-python-client with Apache License 2.0 6 votes vote down vote up
def set_http_session(self, http_session):
        try:
            import requests_kerberos
        except ImportError:
            raise RuntimeError("unable to import requests_kerberos")

        if self._config:
            os.environ["KRB5_CONFIG"] = self._config
        http_session.trust_env = False
        http_session.auth = requests_kerberos.HTTPKerberosAuth(
            mutual_authentication=self._mutual_authentication,
            force_preemptive=self._force_preemptive,
            hostname_override=self._hostname_override,
            sanitize_mutual_error_response=self._sanitize_mutual_error_response,
            principal=self._principal,
            delegate=self._delegate,
            service=self._service_name,
        )
        if self._ca_bundle:
            http_session.verify = self._ca_bundle
        return http_session 
Example #14
Source File: test_connection.py    From grafana-dashboard-builder with Apache License 2.0 5 votes vote down vote up
def test_connection_with_kerberos(post):
    connection = KerberosConnection('https://host')

    post().json.return_value = {'hello': 'world'}

    assert connection.make_request('/uri', {'it\'s': 'alive'}) == {'hello': 'world'}

    capture = Capture()
    post.assert_called_with('https://host/uri', auth=capture, json={"it's": 'alive'}, verify=False)
    assert isinstance(capture.value, HTTPKerberosAuth) 
Example #15
Source File: connection.py    From grafana-dashboard-builder with Apache License 2.0 5 votes vote down vote up
def make_request(self, uri, body=None):
        response = requests.post('{0}{1}'.format(self._host, uri), json=body, auth=HTTPKerberosAuth(), verify=False)
        return response.json() 
Example #16
Source File: rt.py    From ticketutil with GNU General Public License v3.0 5 votes vote down vote up
def _create_requests_session(self):
        """
        Creates a Requests Session and authenticates to base API URL with HTTP Basic Auth or Kerberos Auth.
        We're using a Session to persist cookies across all requests made from the Session instance.
        :return s: Requests Session.
        """
        s = requests.Session()
        # Kerberos Auth
        if self.auth == 'kerberos':
            self.principal = ticket._get_kerberos_principal()
            s.auth = HTTPKerberosAuth(mutual_authentication=DISABLED)
            s.verify = False
        # HTTP Basic Auth
        if isinstance(self.auth, tuple):
            username, password = self.auth
            self.principal = username
            s.params.update({'user': username, 'pass': password})

        # Try to authenticate to auth_url.
        try:
            r = s.get(self.auth_url)
            logger.debug("Create requests session: status code: {0}".format(r.status_code))
            r.raise_for_status()
            # Special case for RT. A 200 status code is still returned if authentication failed. Have to check r.text.
            if '200' not in r.text:
                raise requests.RequestException
            logger.info("Successfully authenticated to {0}".format(self.ticketing_tool))
            return s
        except requests.RequestException as e:
            logger.error("Error authenticating to {0}".format(self.auth_url))
            s.close() 
Example #17
Source File: ticket.py    From ticketutil with GNU General Public License v3.0 5 votes vote down vote up
def _create_requests_session(self):
        """
        Creates a Requests Session and authenticates to base API URL with kerberos-requests.
        We're using a Session to persist cookies across all requests made from the Session instance.
        :return s: Requests Session.
        """
        # TODO: Support other authentication methods.
        # Set up authentication for requests session.
        s = requests.Session()
        if self.auth == 'kerberos':
            self.principal = _get_kerberos_principal()
            s.auth = HTTPKerberosAuth(mutual_authentication=DISABLED)
            s.verify = self.verify
        if isinstance(self.auth, tuple):
            s.auth = self.auth
            s.verify = self.verify

        # Try to authenticate to auth_url.
        try:
            r = s.get(self.auth_url)
            logger.debug("Create requests session: status code: {0}".format(r.status_code))
            r.raise_for_status()
            logger.info("Successfully authenticated to {0}".format(self.ticketing_tool))
            return s
        except requests.RequestException as e:
            logger.error("Error authenticating to {0}".format(self.auth_url))
            logger.error(e)
            s.close() 
Example #18
Source File: restclient.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def _krb_auth():
    """Returns kerberos auth object."""
    auth_principle = None
    if os.name == 'posix':
        # kerberos 1.2.5 doesn't accept None principal. Remove this once fixed.
        auth_principle = ''

    return requests_kerberos.HTTPKerberosAuth(
        mutual_authentication=requests_kerberos.DISABLED,
        principal=auth_principle,
        service=restclientopts.AUTH_PRINCIPAL
    ) 
Example #19
Source File: checks_and_balances_export.py    From ibis with Apache License 2.0 5 votes vote down vote up
def get_job(self, id_val):
        """Retrieve job with provided id
        :param id_val:String
        :return workflow_job:Workflow"""
        workflow_job = None
        query = 'job/' + id_val
        r = requests.get(self.oozie_url + query, auth=HTTPKerberosAuth())
        if r.status_code == 200:  # OK
            my_json = json.dumps(r.json())
            workflow_job = Workflow(my_json)
        else:
            err_msg = "Error retrieving job, {id_val}. Error code: {status}"
            err_msg = err_msg.format(id_val=id_val, status=r.status_code)
            print err_msg
        return r.status_code, workflow_job 
Example #20
Source File: http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_kerberos_auth(config):
    global requests_kerberos
    if requests_kerberos is None:
        import requests_kerberos

        KERBEROS_STRATEGIES['required'] = requests_kerberos.REQUIRED
        KERBEROS_STRATEGIES['optional'] = requests_kerberos.OPTIONAL
        KERBEROS_STRATEGIES['disabled'] = requests_kerberos.DISABLED

    # For convenience
    if config['kerberos_auth'] is None or is_affirmative(config['kerberos_auth']):
        config['kerberos_auth'] = 'required'

    if config['kerberos_auth'] not in KERBEROS_STRATEGIES:
        raise ConfigurationError(
            'Invalid Kerberos strategy `{}`, must be one of: {}'.format(
                config['kerberos_auth'], ' | '.join(KERBEROS_STRATEGIES)
            )
        )

    return requests_kerberos.HTTPKerberosAuth(
        mutual_authentication=KERBEROS_STRATEGIES[config['kerberos_auth']],
        delegate=is_affirmative(config['kerberos_delegate']),
        force_preemptive=is_affirmative(config['kerberos_force_initiate']),
        hostname_override=config['kerberos_hostname'],
        principal=config['kerberos_principal'],
    ) 
Example #21
Source File: test_http.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_kerberos(self):
        instance = {'auth_type': 'kerberos', 'kerberos_auth': 'required'}
        init_config = {}

        # Trigger lazy import
        http = RequestsWrapper(instance, init_config)
        assert isinstance(http.options['auth'], requests_kerberos.HTTPKerberosAuth)

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper(instance, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.REQUIRED,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            )

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper({'auth_type': 'kerberos', 'kerberos_auth': 'optional'}, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.OPTIONAL,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            )

        with mock.patch('datadog_checks.base.utils.http.requests_kerberos.HTTPKerberosAuth') as m:
            RequestsWrapper({'auth_type': 'kerberos', 'kerberos_auth': 'disabled'}, init_config)

            m.assert_called_once_with(
                mutual_authentication=requests_kerberos.DISABLED,
                delegate=False,
                force_preemptive=False,
                hostname_override=None,
                principal=None,
            ) 
Example #22
Source File: webhdfs.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _connect(self):
        self.session = requests.Session()
        if self.kerb:
            from requests_kerberos import HTTPKerberosAuth

            self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs) 
Example #23
Source File: oozie_ws_helper.py    From ibis with Apache License 2.0 4 votes vote down vote up
def get_jobs(self, name=None, user=None, group=None, status=None,
                 offset=1, length=50, job_type='wf'):
        """Retrieve all jobs or filtered jobs
        :param name:String The application name from the
        workflow/coordinator/bundle definition
        :param user:String The user that submitted the job
        :param group:String The group for the job
        :param status:String The status of the job (KILLED, SUCCEEDED, RUNNING)
        :param offset:Int Parameter can be used for pagination
        :param length:Int Parameter can be used for pagination
        :param job_type:String Parameter for job type (wf,
        coordinator or bundle)
        :return status_code:Int, job:Job
        """
        job = None
        # Create query
        query = 'jobs'
        if name or user or group or status or offset or len or job_type:
            query += '?filter='
            if name:
                query += 'name={name}&'.format(name=name)
            if user:
                query += 'user={user}&'.format(user=user)
            if group:
                query += 'group={group}&'.format(group=group)
            if status:
                query += 'status={status}&'.format(status=status)
            if offset:
                query += 'offset={offset}&'.format(offset=offset)
            if length:
                query += 'len={length}&'.format(length=length)
            if job_type:
                query += 'jobtype={job_type}'.format(job_type=job_type)

        r = requests.get(self.oozie_url + query, auth=HTTPKerberosAuth())

        if r.status_code == 200:  # OK
            my_json = json.dumps(r.json())
            job = Job(my_json)
        else:
            print "Error retrieving all jobs. Error code: {status}".format(
                status=r.status_code)
        return r.status_code, job 
Example #24
Source File: checks_and_balances_export.py    From ibis with Apache License 2.0 4 votes vote down vote up
def get_jobs(self, name=None, user=None, group=None, status=None,
                 offset=1, length=50, job_type='wf'):
        """Retrieve all jobs or filtered jobs
        :param name:String The application name from the
        workflow/coordinator/bundle definition
        :param user:String The user that submitted the job
        :param group:String The group for the job
        :param status:String The status of the job (KILLED, SUCCEEDED, RUNNING)
        :param offset:Int Parameter can be used for pagination
        :param length:Int Parameter can be used for pagination
        :param job_type:String Parameter for job type (wf,
        coordinator or bundle)
        :return status_code:Int, job:Job
        """
        job = None
        # Create query
        query = 'jobs'
        if name or user or group or status or offset or length or job_type:
            query += '?filter='
            if name:
                query += 'name={name}&'.format(name=name)
            if user:
                query += 'user={user}&'.format(user=user)
            if group:
                query += 'group={group}&'.format(group=group)
            if status:
                query += 'status={status}&'.format(status=status)
            if offset:
                query += 'offset={offset}&'.format(offset=offset)
            if length:
                query += 'len={length}&'.format(length=length)
            if job_type:
                query += 'jobtype={job_type}'.format(job_type=job_type)

        r = requests.get(self.oozie_url + query, auth=HTTPKerberosAuth())

        if r.status_code == 200:  # OK
            my_json = json.dumps(r.json())
            job = Job(my_json)
        else:
            print "Error retrieving all jobs. Error code: {status}".format(
                status=r.status_code)
        return r.status_code, job