コード例 #1
0
def device_flow_session(client_id, auto=False):
    """Obtain an access token from Azure AD (via device flow) and create
    a Requests session instance ready to make authenticated calls to
    Microsoft Graph.

    client_id = Application ID for registered "Azure AD only" V1-endpoint app
    auto      = whether to copy device code to clipboard and auto-launch browser

    Returns Requests session object if user signed in successfully. The session
    includes the access token in an Authorization header.

    User identity must be an organizational account (ADAL does not support MSAs).
    """
    context = AuthenticationContext(config.AUTHORITY_URL, api_version=None)

    # Authenticate user via email & password
    try:
        token_response = context.acquire_token_with_username_password(
            config.RESOURCE, config.EMAIL, config.PASSWORD, config.CLIENT_ID)
    except:
        print("ERROR: Username or Password incorrect. Closing program")
        exit()

    if not token_response.get('accessToken', None):
        return None

    session = requests.Session()
    session.headers.update({
        'Authorization': f'Bearer {token_response["accessToken"]}',
        'SdkVersion': 'sample-python-adal',
        'x-client-SKU': 'sample-python-adal'
    })
    return session
コード例 #2
0
	def _make_request_headers(self, config):
		if request.headers is None:
			return None, 'No Headers'

		if 'authorization' in request.headers:
			authorization = request.headers['authorization']
		else:
			return None, 'No authorization header'

		if authorization.count(';') != 1:
			return None, 'Invalid authorization header'

		authorization_split = authorization.split(';')

		username = authorization_split[0]
		password = authorization_split[1]

		auth_context = AuthenticationContext(config.authorization_endpoint, api_version=None)
		token_response = auth_context.acquire_token_with_username_password(config.base_url, username, password, config.application_id)

		try:
			self.access_token = token_response['accessToken']
			self.expires_on = datetime.strptime(token_response['expiresOn'], '%Y-%m-%d %H:%M:%S.%f')
		except(KeyError):
			return None, repr(token_response)

		return self._create_header_from_token(), None
コード例 #3
0
ファイル: __init__.py プロジェクト: JordanFaust/dotfiles
def meetings(application_id, email, password, log):
    context = AuthenticationContext(AUTHORITY_URL, api_version=None)

    token = context.acquire_token_with_username_password(
        RESOURCE, email, password, application_id)

    return get_meetings(token, log)
コード例 #4
0
ファイル: __init__.py プロジェクト: JordanFaust/dotfiles
def email_count(application_id, email, password):
    context = AuthenticationContext(AUTHORITY_URL, api_version=None)

    token = context.acquire_token_with_username_password(
        RESOURCE, email, password, application_id)

    inbox = get_primary_inbox(token)
    return get_email_count(inbox, token)
コード例 #5
0
def get_accesstoken(resource_url,username,password):
    domain_name = username.split("@")[1]
    auth_endpoint = get_tennantid(domain_name)
    client_id = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
    context = AuthenticationContext(auth_endpoint.replace("/oauth2/authorize",""))
    token_response = context.acquire_token_with_username_password(("https://" + resource_url),username,password,client_id)
    if "accessToken" in token_response:
        return token_response
    else: 
        raise ValueError('Token Could not be retrieved')
コード例 #6
0
class _AadHelper(object):
    def __init__(
        self,
        kusto_cluster,
        client_id=None,
        client_secret=None,
        username=None,
        password=None,
        authority=None,
    ):
        self.adal_context = AuthenticationContext(
            "https://login.windows.net/{0}".format(authority
                                                   or "microsoft.com"))
        self.kusto_cluster = kusto_cluster
        self.client_id = client_id or "db662dc1-0cfe-4e1c-a843-19a68e65be58"
        self.client_secret = client_secret
        self.username = username
        self.password = password

    def acquire_token(self):
        """A method to acquire tokens from AAD."""
        token_response = self.adal_context.acquire_token(
            self.kusto_cluster, self.username, self.client_id)
        if token_response is not None:
            expiration_date = dateutil.parser.parse(
                token_response["expiresOn"])
            if expiration_date > datetime.utcnow() + timedelta(minutes=5):
                return token_response["accessToken"]

        if self.client_secret is not None and self.client_id is not None:
            token_response = self.adal_context.acquire_token_with_client_credentials(
                self.kusto_cluster, self.client_id, self.client_secret)
        elif self.username is not None and self.password is not None:
            token_response = self.adal_context.acquire_token_with_username_password(
                self.kusto_cluster, self.username, self.password,
                self.client_id)
        else:
            code = self.adal_context.acquire_user_code(self.kusto_cluster,
                                                       self.client_id)
            print(code["message"])
            webbrowser.open(code["verification_url"])
            token_response = self.adal_context.acquire_token_with_device_code(
                self.kusto_cluster, code, self.client_id)

        return token_response["accessToken"]
コード例 #7
0
def main(argv):
    try:
        options, args = getopt.getopt(argv, 'hu:p:a:r:c:')
    except getopt.GetoptError:
        printUsage()
        sys.exit(-1)

    username = ''
    password = ''
    authority = ''
    resource = ''

    clientId = ''

    for option, arg in options:
        if option == '-h':
            printUsage()
            sys.exit()
        elif option == '-u':
            username = arg
        elif option == '-p':
            password = arg
        elif option == '-a':
            authority = arg
        elif option == '-r':
            resource = arg
        elif option == '-c':
            clientId = arg

    if username == '' or password == '' or authority == '' or resource == '' or clientId == '':
        printUsage()
        sys.exit(-1)

    # Find everything after the last '/' and replace it with 'token'
    if not authority.endswith('token'):
        regex = re.compile('^(.*[\/])')
        match = regex.match(authority)
        authority = match.group()
        authority = authority + username.split('@')[1]

    auth_context = AuthenticationContext(authority)
    token = auth_context.acquire_token_with_username_password(
        resource, username, password, clientId)
    print(token["accessToken"])
コード例 #8
0
class _MyAadHelper(object):
    def __init__(self, kcsb, default_clientid):
        authority = kcsb.authority_id or "common"
        self._resource = "{0.scheme}://{0.hostname}".format(
            urlparse(kcsb.data_source))
        self._adal_context = AuthenticationContext(
            "https://login.microsoftonline.com/{0}".format(authority))
        self._username = None
        if all([kcsb.aad_user_id, kcsb.password]):
            self._authentication_method = AuthenticationMethod.aad_username_password
            self._client_id = default_clientid
            self._username = kcsb.aad_user_id
            self._password = kcsb.password
        elif all([kcsb.application_client_id, kcsb.application_key]):
            self._authentication_method = AuthenticationMethod.aad_application_key
            self._client_id = kcsb.application_client_id
            self._client_secret = kcsb.application_key
        elif all([
                kcsb.application_client_id, kcsb.application_certificate,
                kcsb.application_certificate_thumbprint
        ]):
            self._authentication_method = AuthenticationMethod.aad_application_certificate
            self._client_id = kcsb.application_client_id
            self._certificate = kcsb.application_certificate
            self._thumbprint = kcsb.application_certificate_thumbprint
        else:
            self._authentication_method = AuthenticationMethod.aad_device_login
            self._client_id = default_clientid

    def acquire_token(self, **options):
        """Acquire tokens from AAD."""
        token = self._adal_context.acquire_token(self._resource,
                                                 self._username,
                                                 self._client_id)
        if token is not None:
            expiration_date = dateutil.parser.parse(
                token[TokenResponseFields.EXPIRES_ON])
            if expiration_date > datetime.now() + timedelta(minutes=1):
                return self._get_header(token)
            if TokenResponseFields.REFRESH_TOKEN in token:
                token = self._adal_context.acquire_token_with_refresh_token(
                    token[TokenResponseFields.REFRESH_TOKEN], self._client_id,
                    self._resource)
                if token is not None:
                    return self._get_header(token)

        if self._authentication_method is AuthenticationMethod.aad_username_password:
            token = self._adal_context.acquire_token_with_username_password(
                self._resource, self._username, self._password,
                self._client_id)
        elif self._authentication_method is AuthenticationMethod.aad_application_key:
            token = self._adal_context.acquire_token_with_client_credentials(
                self._resource, self._client_id, self._client_secret)
        elif self._authentication_method is AuthenticationMethod.aad_device_login:
            # print(code[OAuth2DeviceCodeResponseParameters.MESSAGE])
            # webbrowser.open(code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL])
            # token = self._adal_context.acquire_token_with_device_code(
            #     self._resource, code, self._client_id
            # )
            code: dict = self._adal_context.acquire_user_code(
                self._resource, self._client_id)
            url = code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]
            device_code = code[
                OAuth2DeviceCodeResponseParameters.USER_CODE].strip()

            html_str = ("""<!DOCTYPE html>
                <html><body>

                <!-- h1 id="user_code_p"><b>""" + device_code +
                        """</b><br></h1-->

                <input  id="kql_MagicCodeAuthInput" type="text" readonly style="font-weight: bold; border: none;" size = '"""
                        + str(len(device_code)) + """' value='""" +
                        device_code + """'>

                <button id='kql_MagicCodeAuth_button', onclick="this.style.visibility='hidden';kql_MagicCodeAuthFunction()">Copy code to clipboard and authenticate</button>

                <script>
                var kql_MagicUserCodeAuthWindow = null
                function kql_MagicCodeAuthFunction() {
                    /* Get the text field */
                    var copyText = document.getElementById("kql_MagicCodeAuthInput");

                    /* Select the text field */
                    copyText.select();

                    /* Copy the text inside the text field */
                    document.execCommand("copy");

                    /* Alert the copied text */
                    // alert("Copied the text: " + copyText.value);

                    var w = screen.width / 2;
                    var h = screen.height / 2;
                    params = 'width='+w+',height='+h
                    kql_MagicUserCodeAuthWindow = window.open('""" + url +
                        """', 'kql_MagicUserCodeAuthWindow', params);

                    // TODO: save selected cell index, so that the clear will be done on the lince cell
                }
                </script>

                </body></html>""")

            if options.get("notebook_app") in ["visualstudiocode", "ipython"]:
                Display.show_window('verification_url', url, **options)
                # Display.showInfoMessage("Code: {0}".format(device_code))
                Display.showInfoMessage(
                    "Copy code: {0} to verification url: {1} and authenticate".
                    format(device_code, url), **options)
            else:
                Display.show_html(html_str)

            try:
                token = self._adal_context.acquire_token_with_device_code(
                    self._resource, code, self._client_id)
            finally:
                html_str = """<!DOCTYPE html>
                    <html><body><script>

                        // close authentication window
                        if (kql_MagicUserCodeAuthWindow && kql_MagicUserCodeAuthWindow.opener != null && !kql_MagicUserCodeAuthWindow.closed) {
                            kql_MagicUserCodeAuthWindow.close()
                        }
                        // TODO: make sure, you clear the right cell. BTW, not sure it is a must to do any clearing

                        // clear output cell
                        Jupyter.notebook.clear_output(Jupyter.notebook.get_selected_index())

                        // TODO: if in run all mode, move to last cell, otherwise move to next cell
                        // move to next cell

                    </script></body></html>"""

                Display.show_html(html_str)
        elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
            token = self._adal_context.acquire_token_with_client_certificate(
                self._resource, self._client_id, self._certificate,
                self._thumbprint)
        else:
            raise AuthenticationError("Unknown authentication method.")
        return self._get_header(token)

    def _get_header(self, token):
        return "{0} {1}".format(token[TokenResponseFields.TOKEN_TYPE],
                                token[TokenResponseFields.ACCESS_TOKEN])
コード例 #9
0
class _AadHelper(object):
    def __init__(self, kcsb):
        authority = kcsb.authority_id or "microsoft.com"
        self._kusto_cluster = "{0.scheme}://{0.hostname}".format(
            urlparse(kcsb.data_source))
        self._adal_context = AuthenticationContext("https://{0}/{1}".format(
            AADConstants.WORLD_WIDE_AUTHORITY, authority))
        self._username = None
        if all([kcsb.aad_user_id, kcsb.password]):
            self._authentication_method = AuthenticationMethod.aad_username_password
            self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"
            self._username = kcsb.aad_user_id
            self._password = kcsb.password
        elif all([kcsb.application_client_id, kcsb.application_key]):
            self._authentication_method = AuthenticationMethod.aad_application_key
            self._client_id = kcsb.application_client_id
            self._client_secret = kcsb.application_key
        elif all([
                kcsb.application_client_id,
                kcsb.application_certificate,
                kcsb.application_certificate_thumbprint,
        ]):
            self._authentication_method = AuthenticationMethod.aad_application_certificate
            self._client_id = kcsb.application_client_id
            self._certificate = kcsb.application_certificate
            self._thumbprint = kcsb.application_certificate_thumbprint
        else:
            self._authentication_method = AuthenticationMethod.aad_device_login
            self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"

    def acquire_token(self):
        """Acquire tokens from AAD."""
        token = self._adal_context.acquire_token(self._kusto_cluster,
                                                 self._username,
                                                 self._client_id)
        if token is not None:
            expiration_date = dateutil.parser.parse(
                token[TokenResponseFields.EXPIRES_ON])
            if expiration_date > datetime.now() + timedelta(minutes=1):
                return _get_header(token)
            if TokenResponseFields.REFRESH_TOKEN in token:
                token = self._adal_context.acquire_token_with_refresh_token(
                    token[TokenResponseFields.REFRESH_TOKEN], self._client_id,
                    self._kusto_cluster)
                if token is not None:
                    return _get_header(token)

        if self._authentication_method is AuthenticationMethod.aad_username_password:
            token = self._adal_context.acquire_token_with_username_password(
                self._kusto_cluster, self._username, self._password,
                self._client_id)
        elif self._authentication_method is AuthenticationMethod.aad_application_key:
            token = self._adal_context.acquire_token_with_client_credentials(
                self._kusto_cluster, self._client_id, self._client_secret)
        elif self._authentication_method is AuthenticationMethod.aad_device_login:
            code = self._adal_context.acquire_user_code(
                self._kusto_cluster, self._client_id)
            print(code[OAuth2DeviceCodeResponseParameters.MESSAGE])
            webbrowser.open(
                code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL])
            token = self._adal_context.acquire_token_with_device_code(
                self._kusto_cluster, code, self._client_id)
        elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
            token = self._adal_context.acquire_token_with_client_certificate(
                self._kusto_cluster, self._client_id, self._certificate,
                self._thumbprint)
        else:
            raise KustoClientError(
                "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod"
            )

        return _get_header(token)
コード例 #10
0
class _AadHelper:
    authentication_method = None
    auth_context = None
    username = None
    kusto_uri = None
    authority_uri = None
    client_id = None
    password = None
    thumbprint = None
    certificate = None
    msi_params = None
    token_provider = None

    def __init__(self, kcsb):
        self.kusto_uri = "{0.scheme}://{0.hostname}".format(
            urlparse(kcsb.data_source))
        self.username = None

        if all([kcsb.aad_user_id, kcsb.password]):
            self.authentication_method = AuthenticationMethod.aad_username_password
            self.client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"
            self.username = kcsb.aad_user_id
            self.password = kcsb.password
        elif all([kcsb.application_client_id, kcsb.application_key]):
            self.authentication_method = AuthenticationMethod.aad_application_key
            self.client_id = kcsb.application_client_id
            self.client_secret = kcsb.application_key
        elif all([
                kcsb.application_client_id, kcsb.application_certificate,
                kcsb.application_certificate_thumbprint
        ]):
            self.authentication_method = AuthenticationMethod.aad_application_certificate
            self.client_id = kcsb.application_client_id
            self.certificate = kcsb.application_certificate
            self.thumbprint = kcsb.application_certificate_thumbprint
        elif kcsb.msi_authentication:
            self.authentication_method = AuthenticationMethod.aad_msi
            self.msi_params = kcsb.msi_parameters
            return
        elif any([kcsb.user_token, kcsb.application_token]):
            self.token = kcsb.user_token or kcsb.application_token
            self.authentication_method = AuthenticationMethod.aad_token
            return
        elif kcsb.az_cli:
            self.authentication_method = AuthenticationMethod.az_cli_profile
            return
        elif kcsb.token_provider:
            self.authentication_method = AuthenticationMethod.token_provider
            self.token_provider = kcsb.token_provider
        else:
            self.authentication_method = AuthenticationMethod.aad_device_login
            self.client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"

        authority = kcsb.authority_id or "common"
        aad_authority_uri = os.environ.get("AadAuthorityUri", CLOUD_LOGIN_URL)
        self.authority_uri = aad_authority_uri + authority if aad_authority_uri.endswith(
            "/") else aad_authority_uri + "/" + authority

    def acquire_authorization_header(self):
        """Acquire tokens from AAD."""
        try:
            return self._acquire_authorization_header()
        except (AdalError, KustoClientError) as error:
            if self.authentication_method is AuthenticationMethod.aad_username_password:
                kwargs = {
                    "username": self.username,
                    "client_id": self.client_id
                }
            elif self.authentication_method is AuthenticationMethod.aad_application_key:
                kwargs = {"client_id": self.client_id}
            elif self.authentication_method is AuthenticationMethod.aad_device_login:
                kwargs = {"client_id": self.client_id}
            elif self.authentication_method is AuthenticationMethod.aad_application_certificate:
                kwargs = {
                    "client_id": self.client_id,
                    "thumbprint": self.thumbprint
                }
            elif self.authentication_method is AuthenticationMethod.aad_msi:
                kwargs = self.msi_params
            elif self.authentication_method is AuthenticationMethod.token_provider:
                kwargs = {}
            else:
                raise error

            kwargs["resource"] = self.kusto_uri

            if self.authentication_method is AuthenticationMethod.aad_msi:
                kwargs["authority"] = AuthenticationMethod.aad_msi.value
            elif self.authentication_method is AuthenticationMethod.token_provider:
                kwargs["authority"] = AuthenticationMethod.token_provider.value
            elif self.auth_context is not None:
                kwargs["authority"] = self.auth_context.authority.url

            raise KustoAuthenticationError(self.authentication_method.value,
                                           error, **kwargs)

    def _acquire_authorization_header(self) -> str:
        # Token was provided by caller
        if self.authentication_method is AuthenticationMethod.aad_token:
            return _get_header("Bearer", self.token)

        if self.authentication_method is AuthenticationMethod.token_provider:
            caller_token = self.token_provider()
            if not isinstance(caller_token, str):
                raise KustoClientError(
                    "Token provider returned something that is not a string ["
                    + str(type(caller_token)) + "]")

            return _get_header("Bearer", caller_token)

        # Obtain token from MSI endpoint
        if self.authentication_method == AuthenticationMethod.aad_msi:
            token = self.get_token_from_msi()
            return _get_header_from_dict(token)

        refresh_token = None

        if self.authentication_method == AuthenticationMethod.az_cli_profile:
            stored_token = _get_azure_cli_auth_token()

            if (TokenResponseFields.REFRESH_TOKEN in stored_token
                    and TokenResponseFields._CLIENT_ID in stored_token
                    and TokenResponseFields._AUTHORITY in stored_token):
                self.client_id = stored_token[TokenResponseFields._CLIENT_ID]
                self.username = stored_token[TokenResponseFields.USER_ID]
                self.authority_uri = stored_token[
                    TokenResponseFields._AUTHORITY]
                refresh_token = stored_token[TokenResponseFields.REFRESH_TOKEN]

        if self.auth_context is None:
            self.auth_context = AuthenticationContext(self.authority_uri)

        if refresh_token is not None:
            token = self.auth_context.acquire_token_with_refresh_token(
                refresh_token, self.client_id, self.kusto_uri)
        else:
            token = self.auth_context.acquire_token(self.kusto_uri,
                                                    self.username,
                                                    self.client_id)

        if token is not None:
            expiration_date = dateutil.parser.parse(
                token[TokenResponseFields.EXPIRES_ON])
            if expiration_date > datetime.now() + timedelta(minutes=1):
                return _get_header_from_dict(token)
            if TokenResponseFields.REFRESH_TOKEN in token:
                token = self.auth_context.acquire_token_with_refresh_token(
                    token[TokenResponseFields.REFRESH_TOKEN], self.client_id,
                    self.kusto_uri)
                if token is not None:
                    return _get_header_from_dict(token)

        # obtain token from AAD
        if self.authentication_method is AuthenticationMethod.aad_username_password:
            token = self.auth_context.acquire_token_with_username_password(
                self.kusto_uri, self.username, self.password, self.client_id)
        elif self.authentication_method is AuthenticationMethod.aad_application_key:
            token = self.auth_context.acquire_token_with_client_credentials(
                self.kusto_uri, self.client_id, self.client_secret)
        elif self.authentication_method is AuthenticationMethod.aad_device_login:
            code = self.auth_context.acquire_user_code(self.kusto_uri,
                                                       self.client_id)
            print(code[OAuth2DeviceCodeResponseParameters.MESSAGE])
            webbrowser.open(
                code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL])
            token = self.auth_context.acquire_token_with_device_code(
                self.kusto_uri, code, self.client_id)
        elif self.authentication_method is AuthenticationMethod.aad_application_certificate:
            token = self.auth_context.acquire_token_with_client_certificate(
                self.kusto_uri, self.client_id, self.certificate,
                self.thumbprint)
        else:
            raise KustoClientError(
                "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod"
            )

        return _get_header_from_dict(token)

    def get_token_from_msi(self) -> dict:
        try:
            credentials = MSIAuthentication(**self.msi_params)
        except Exception as e:
            raise KustoClientError("Failed to obtain MSI context for [" +
                                   str(self.msi_params) + "]\n" + str(e))

        return credentials.token
コード例 #11
0
class _AadHelper(object):
    def __init__(self, kcsb):
        if any([kcsb.user_token, kcsb.application_token]):
            self._token = kcsb.user_token or kcsb.application_token
            self._authentication_method = AuthenticationMethod.aad_token
            return

        authority = kcsb.authority_id or "common"
        self._kusto_cluster = "{0.scheme}://{0.hostname}".format(
            urlparse(kcsb.data_source))
        self._adal_context = AuthenticationContext(
            "https://login.microsoftonline.com/{0}".format(authority))
        self._username = None
        if all([kcsb.aad_user_id, kcsb.password]):
            self._authentication_method = AuthenticationMethod.aad_username_password
            self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"
            self._username = kcsb.aad_user_id
            self._password = kcsb.password
        elif all([kcsb.application_client_id, kcsb.application_key]):
            self._authentication_method = AuthenticationMethod.aad_application_key
            self._client_id = kcsb.application_client_id
            self._client_secret = kcsb.application_key
        elif all([
                kcsb.application_client_id, kcsb.application_certificate,
                kcsb.application_certificate_thumbprint
        ]):
            self._authentication_method = AuthenticationMethod.aad_application_certificate
            self._client_id = kcsb.application_client_id
            self._certificate = kcsb.application_certificate
            self._thumbprint = kcsb.application_certificate_thumbprint
        else:
            self._authentication_method = AuthenticationMethod.aad_device_login
            self._client_id = "db662dc1-0cfe-4e1c-a843-19a68e65be58"

    def acquire_authorization_header(self):
        """Acquire tokens from AAD."""
        try:
            return self._acquire_authorization_header()
        except AdalError as error:
            if self._authentication_method is AuthenticationMethod.aad_username_password:
                kwargs = {
                    "username": self._username,
                    "client_id": self._client_id
                }
            elif self._authentication_method is AuthenticationMethod.aad_application_key:
                kwargs = {"client_id": self._client_id}
            elif self._authentication_method is AuthenticationMethod.aad_device_login:
                kwargs = {"client_id": self._client_id}
            elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
                kwargs = {
                    "client_id": self._client_id,
                    "thumbprint": self._thumbprint
                }
            else:
                raise error

            kwargs["resource"] = self._kusto_cluster
            kwargs["authority"] = self._adal_context.authority.url

            raise KustoAuthenticationError(self._authentication_method.value,
                                           error, **kwargs)

    def _acquire_authorization_header(self):
        if self._authentication_method is AuthenticationMethod.aad_token:
            return _get_header("Bearer", self._token)

        token = self._adal_context.acquire_token(self._kusto_cluster,
                                                 self._username,
                                                 self._client_id)
        if token is not None:
            expiration_date = dateutil.parser.parse(
                token[TokenResponseFields.EXPIRES_ON])
            if expiration_date > datetime.now() + timedelta(minutes=1):
                return _get_header_from_dict(token)
            if TokenResponseFields.REFRESH_TOKEN in token:
                token = self._adal_context.acquire_token_with_refresh_token(
                    token[TokenResponseFields.REFRESH_TOKEN], self._client_id,
                    self._kusto_cluster)
                if token is not None:
                    return _get_header_from_dict(token)

        if self._authentication_method is AuthenticationMethod.aad_username_password:
            token = self._adal_context.acquire_token_with_username_password(
                self._kusto_cluster, self._username, self._password,
                self._client_id)
        elif self._authentication_method is AuthenticationMethod.aad_application_key:
            token = self._adal_context.acquire_token_with_client_credentials(
                self._kusto_cluster, self._client_id, self._client_secret)
        elif self._authentication_method is AuthenticationMethod.aad_device_login:
            code = self._adal_context.acquire_user_code(
                self._kusto_cluster, self._client_id)
            print(code[OAuth2DeviceCodeResponseParameters.MESSAGE])
            webbrowser.open(
                code[OAuth2DeviceCodeResponseParameters.VERIFICATION_URL])
            token = self._adal_context.acquire_token_with_device_code(
                self._kusto_cluster, code, self._client_id)
        elif self._authentication_method is AuthenticationMethod.aad_application_certificate:
            token = self._adal_context.acquire_token_with_client_certificate(
                self._kusto_cluster, self._client_id, self._certificate,
                self._thumbprint)
        else:
            raise KustoClientError(
                "Please choose authentication method from azure.kusto.data.security.AuthenticationMethod"
            )

        return _get_header_from_dict(token)
コード例 #12
0
class _MyAadHelper(object):
    def __init__(self,
                 kusto_cluster,
                 client_id=None,
                 client_secret=None,
                 username=None,
                 password=None,
                 authority=None):
        self.adal_context = AuthenticationContext(
            'https://login.windows.net/{0}'.format(authority
                                                   or 'microsoft.com'))
        self.kusto_cluster = kusto_cluster
        self.client_id = client_id or "db662dc1-0cfe-4e1c-a843-19a68e65be58"
        self.client_secret = client_secret
        self.username = username
        self.password = password

    def acquire_token(self):
        """ A method to acquire tokens from AAD. """
        # print("my_aad_helper_acquire_token")
        token_response = self.adal_context.acquire_token(
            self.kusto_cluster, self.username, self.client_id)

        if token_response is not None:
            expiration_date = dateutil.parser.parse(
                token_response['expiresOn'])
            if expiration_date > datetime.utcnow() + timedelta(minutes=5):
                return token_response['accessToken']

        if self.client_secret is not None and self.client_id is not None:
            token_response = self.adal_context.acquire_token_with_client_credentials(
                self.kusto_cluster, self.client_id, self.client_secret)
        elif self.username is not None and self.password is not None:
            token_response = self.adal_context.acquire_token_with_username_password(
                self.kusto_cluster, self.username, self.password,
                self.client_id)
        else:
            code = self.adal_context.acquire_user_code(self.kusto_cluster,
                                                       self.client_id)

            url = code['verification_url']
            device_code = code["user_code"].strip()

            html_str = """<!DOCTYPE html>
                <html><body>

                <!-- h1 id="user_code_p"><b>""" + device_code + """</b><br></h1-->

                <input  id="kqlMagicCodeAuthInput" type="text" readonly style="font-weight: bold; border: none;" size = '""" + str(
                len(device_code)) + """' value='""" + device_code + """'>

                <button id='kqlMagicCodeAuth_button', onclick="this.style.visibility='hidden';kqlMagicCodeAuthFunction()">Copy code to clipboard and authenticate</button>

                <script>
                var kqlMagicUserCodeAuthWindow = null
                function kqlMagicCodeAuthFunction() {
                    /* Get the text field */
                    var copyText = document.getElementById("kqlMagicCodeAuthInput");

                    /* Select the text field */
                    copyText.select();

                    /* Copy the text inside the text field */
                    document.execCommand("copy");

                    /* Alert the copied text */
                    // alert("Copied the text: " + copyText.value);

                    var w = screen.width / 2;
                    var h = screen.height / 2;
                    params = 'width='+w+',height='+h
                    kqlMagicUserCodeAuthWindow = window.open('""" + url + """', 'kqlMagicUserCodeAuthWindow', params);
                }
                </script>

                </body></html>"""

            Display.show(html_str)
            # webbrowser.open(code['verification_url'])
            try:
                token_response = self.adal_context.acquire_token_with_device_code(
                    self.kusto_cluster, code, self.client_id)
            finally:
                html_str = """<!DOCTYPE html>
                    <html><body><script>

                        // close authentication window
                        if (kqlMagicUserCodeAuthWindow && kqlMagicUserCodeAuthWindow.opener != null && !kqlMagicUserCodeAuthWindow.closed) {
                            kqlMagicUserCodeAuthWindow.close()
                        }
                        // clear output cell 
                        Jupyter.notebook.clear_output(Jupyter.notebook.get_selected_index())
                        // move to next cell

                    </script></body></html>"""

                Display.show(html_str)

        return token_response['accessToken']
コード例 #13
0
ファイル: kernel.py プロジェクト: bernhard-42/db-12-kernel
class DB12Kernel(MetaKernel):
    app_name = "db_12_kernel"
    implementation = "A Jupyter kernel for Databricks using REST API 1.2"
    implementation_version = "0.1.0"
    language = "python"
    language_version = "3.6+"
    banner = "Databricks REST API 1.2 Kernel - evaluates Python statements on a remote Databricks cluster"
    language_info = {
        "mimetype": "text/x-python",
        "name": "python",
        "file_extension": ".py",
        "help_links": MetaKernel.help_links,
    }
    kernel_json = {
        "argv":
        [sys.executable, "-m", "db_12_kernel", "-f", "{connection_file}"],
        "display_name": "DB Kernel",
        "language": "python",
        "name": "db_12_kernel",
    }

    profile = Unicode(None, allow_none=True).tag(config=True)
    host = Unicode(None, allow_none=True).tag(config=True)
    cluster = Unicode(None, allow_none=True).tag(config=True)
    org = Unicode(None, allow_none=True).tag(config=True)
    tenant = Unicode(None, allow_none=True).tag(config=True)
    user = Unicode(None, allow_none=True).tag(config=True)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        #        self.log = logging.getLogger(self.__class__.__name__)
        self.log.setLevel(logging.DEBUG)
        self.log.info("Current Databricks config")
        self.log.info("- Profile %s", self.profile)
        self.log.info("- Cluster %s", self.cluster)
        # All clusters
        self.command = None
        self.token = None
        # Azure clusters for User AAD Token
        self.password = None

    #     self._get_config()

    def _get_config(self, config_file="~/.dbjl-light"):
        if self.profile is None:
            with open(os.path.expanduser(config_file)) as fd:
                db_config = yaml.safe_load(fd)
            self.cluster = db_config["cluster"]
            self.host = db_config["host"]
            self.org = db_config["org"]
            self.tenant = db_config["tenant"]
            self.user = db_config["user"]
            self.token = None
        else:
            self.log.info("profile2 %s", self.profile)
            self.host, self.token = get_db_config(self.profile)
            self.log.info("host %s", self.host)
            self.org = None
            self.tenant = None
            self.user = None

        self.host = self.host.rstrip("/")

    def _decode_token(self, token):
        self.log.info(jwt.decode(token, verify=False))

    def _debug(self, *args):
        self.redirect_to_log = True
        self.log.debug(" ".join([str(a) for a in args]) + "\n")
        self.redirect_to_log = False

    def _strip_out(self, result):
        return re.sub(r"^(Out\[\d+\]: )", "", result)

    def _get_password(self, prompt):
        # Using a private API here. No idea how to avoid this ...
        return self._input_request(str(prompt),
                                   self._parent_ident,
                                   self._parent_header,
                                   password=True)

    def _login(self):
        if self.token is None and self.org is not None:
            # Azure, use User AAD Token
            password = self._get_password("Password for '%s': " % self.user)
            authority_url = "https://login.microsoftonline.com/%s" % self.tenant
            self.auth_context = AuthenticationContext(authority_url)

            token_response = self.auth_context.acquire_token_with_username_password(
                DB_RESOURCE, self.user, password, self.client_id)

            self.token = token_response.get("accessToken", None)
            self.refresh_token = token_response.get("refreshToken", None)
            self._decode_token(self.access_token)

    def _create_context(self):
        if self.command == None:
            if self.token is None:
                self._get_config()
            self.log.info("Creating execution context\n")
            self.log.debug("Current config:")
            self.log.debug("- Profile: %s", self.profile)
            self.log.debug("- Databricks host: %s", self.host)
            self.log.debug("- Cluster: %s", self.cluster)
            if self.org is not None:
                self.log.info("- Organsation: %s", self.org)
            if self.user is not None:
                self.log.info("- User: %s\n", self.user)

            self._login()

            self.command = RemoteCommand(
                self.host,
                self.cluster,
                self.org,
                self.token,
                self.log,
                self.Print,
            )
            if self.command.start_context():
                self.Print("Importing jedi and pydoc")
                self.command.execute("import jedi, pydoc")
                self.Print("Patching matplotlib.pyplot.show")
                self.command.execute(SHOW_TEMPLATE)
                try:
                    self.Print("Generating Spark UI URL")
                    response = self.command.execute(
                        "sc.getConf().get('spark.databricks.sparkContextId')")
                    print(response)
                    context_id = self._strip_out(response[1])[1:-1]
                    url = "%ssparkui/%s/driver-%s/jobs?o=%s" % (
                        self.host,
                        self.cluster,
                        context_id,
                        self.org,
                    )
                    url = "%s/?o=%s#/setting/clusters/%s/sparkUi" % (
                        self.host,
                        self.org,
                        self.cluster,
                    )
                    self.command.execute("SPARK_UI='%s'" % url)
                    self.Display(
                        HTML(
                            "Databricks execution context created: <a href='%s'>Spark UI</a> (variable SPARK_UI)"
                            % url),
                        clear_output=True,
                    )

                except:
                    self.Print("Cannot automatically determine SPARK UI URL")
                    self.Display(HTML("Databricks execution context created"),
                                 clear_output=True)
            else:
                self.Display(
                    HTML("Could not start Databricks execution context"),
                    clear_output=False,
                )

    def _close_context(self):
        if self.command is not None:
            self.command.close_context()

    def get_usage(self):
        return "This is a Databricks REST Kernel. It implements a remote Python interpreter."

    def do_execute_direct(self, code):
        self._debug(code)
        self._create_context()

        response = self.command.execute(code)
        if response[0]:
            try:
                result = eval(self._strip_out(response[1]))
            except:
                result = self._strip_out(response[1])

            self._debug("result=", result, type(result))

            if isinstance(result, dict):
                if result.get("client", None) == "__dbjl_light__":
                    if result["format"] in ["png", "jpg", "jpeg"]:
                        self.Display(Image(base64.b64decode(result["data"])))
                        return None
                    elif result["format"] == "html":
                        self.Display(HTML(result["data"]))
                        return None
                    elif result["format"] == "svg":
                        self.Display(SVG(result["data"]))
                        return None

            if result == "":
                return None
            elif isinstance(result, str):
                self.Print(result)
            else:
                return result
        else:
            self.Display(HTML("Summary: " + response[1]["summary"]))
            self.Print(response[1]["cause"])

    def get_completions(self, info):
        self._create_context()

        text = info["code"]
        lines = split_lines(text)
        position = (info["line_num"], info["column"])
        code = COMPLETION_TEMPLATE % (text, str(lines), str(position))

        response = self.command.execute(code)
        result = self._strip_out(response[1])
        before, _, completions = eval(result)
        completions = [before + c for c in completions]
        return [c[info["start"]:] for c in completions]

    def get_kernel_help_on(self, info, level=1, none_on_fail=False):
        last = info["obj"]
        default = None if none_on_fail else ('No help available for "%s"' %
                                             last)
        code = HELP_TEMPLATE % (last, default)
        response = self.command.execute(code)
        result = (self._strip_out(response[1]).replace(
            "``", "`").encode("utf-8").decode("unicode_escape").strip('"'))
        self.Print(result)

    def restart_kernel(self):
        self._close_context()

    def do_shutdown(self, restart):
        self._close_context()
        return super().do_shutdown(restart)
コード例 #14
0
from adal import AuthenticationContext
from dynamics365crm.client import Client

DYNAMIC_RESOURCE = 'https://edge.crm2.dynamics.com/'

auth_context = AuthenticationContext(
    'https://login.microsoftonline.com/76b77ddd-7462-4810-b24e-bc1668ab6f19')
token = auth_context.acquire_token_with_username_password(
    'https://edge.crm2.dynamics.com/', '*****@*****.**', 'Murilao23',
    '87dafbc3-e1eb-418f-abbb-3d526d1508d4')
#'e84e50cb-b9df-4311-b672-b47951e6a2c7')
client = Client(DYNAMIC_RESOURCE)
client.set_token(token["accessToken"])