Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
def device_flow_session(client_id, auto=False):

    ctx = AuthenticationContext(AUTHORITY_URL, api_version=None)
    device_code = ctx.acquire_user_code(RESOURCE, client_id)

    if auto:
        pyperclip.copy(device_code['user_code'])
        webbrowser.open(device_code['verification_url'])
        print(
            f'The code {device_code["user_code"]} has been copied to your clipboard, '
            f'and your web browser is opening {device_code["verification_url"]}. '
            'Paste the code to sign in.')
    else:
        print(device_code['message'])

    token_response = ctx.acquire_token_with_device_code(
        RESOURCE, device_code, client_id)
    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
Ejemplo n.º 3
0
    def _set_adal_context(self, adal_context=None, adal_context_sso=None):
        "set the adal context"
        self._authority_uri = f"{self._aad_login_url}/{self._authority}"

        self._adal_context = adal_context
        if self._adal_context is None:
            if global_adal_context.get(self._authority_uri) is None:
                global_adal_context[
                    self._authority_uri] = AuthenticationContext(
                        self._authority_uri, cache=None)
            self._adal_context = global_adal_context.get(self._authority_uri)

        self._adal_context_sso = None
        if self._options.get("enable_sso"):
            self._adal_context_sso = adal_context_sso
            if self._adal_context_sso is None:
                if global_adal_context_sso.get(self._authority_uri) is None:
                    cache = AdalTokenCache.get_cache(self._authority_uri,
                                                     **self._options)
                    if cache is not None:
                        global_adal_context_sso[
                            self._authority_uri] = AuthenticationContext(
                                self._authority_uri, cache=cache)
                self._adal_context_sso = global_adal_context_sso.get(
                    self._authority_uri)
Ejemplo n.º 4
0
 def __init__(
     self,
     app_id: str,
     password: str,
     channel_auth_tenant: str = None,
     oauth_scope: str = None,
 ):
     """
     Initializes a new instance of MicrosoftAppCredentials class
     :param app_id: The Microsoft app ID.
     :param app_password: The Microsoft app password.
     :param channel_auth_tenant: Optional. The oauth token tenant.
     """
     # The configuration property for the Microsoft app ID.
     self.microsoft_app_id = app_id
     # The configuration property for the Microsoft app Password.
     self.microsoft_app_password = password
     tenant = (
         channel_auth_tenant
         if channel_auth_tenant
         else AuthenticationConstants.DEFAULT_CHANNEL_AUTH_TENANT
     )
     self.oauth_endpoint = (
         AuthenticationConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL_PREFIX + tenant
     )
     self.oauth_scope = (
         oauth_scope or AuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER
     )
     self.token_cache_key = app_id + self.oauth_scope + "-cache" if app_id else None
     self.authentication_context = AuthenticationContext(self.oauth_endpoint)
Ejemplo n.º 5
0
def device_flow_session(client_id, auto=True):

    ctx = AuthenticationContext(config.AUTHORITY_URL, api_version=None)
    device_code = ctx.acquire_user_code(config.RESOURCE, client_id)

    # display user instructions
    if auto:

        print(
            f'Le code {device_code["user_code"]} a ete copie dans le presse-papier '
            f' et votre navigateur est en train d´ouvrir la page {device_code["verification_url"]}. '
            'Coller le code pour se connecter.')
        pyperclip.copy(device_code['user_code'])  # copy user code to clipboard
        webbrowser.open(device_code['verification_url'])  # open browser

    else:
        print(device_code['message'])

    token_response = ctx.acquire_token_with_device_code(
        config.RESOURCE, device_code, client_id)
    if not token_response.get('accessToken', None):

        return None

    session = requests.Session()
    session.headers.update(
        {'Authorization': f'Bearer {token_response["accessToken"]}'})

    return session
Ejemplo n.º 6
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
Ejemplo n.º 7
0
def acquire_token_with_device_code(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).
    """
    ctx = AuthenticationContext(AUTHORITY_URL, api_version=None)
    device_code = ctx.acquire_user_code(RESOURCE,
                                        client_id)

    # display user instructions
    if auto:
        pyperclip.copy(device_code['user_code'])  # copy user code to clipboard
        webbrowser.open(device_code['verification_url'])  # open browser
        print(f'The code {device_code["user_code"]} has been copied to your clipboard, '
              f'and your web browser is opening {device_code["verification_url"]}. '
              'Paste the code to sign in.')
    else:
        print(device_code['message'])

    return ctx.acquire_token_with_device_code(RESOURCE,
                                              device_code,
                                              client_id)
Ejemplo n.º 8
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
Ejemplo n.º 9
0
 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"
Ejemplo n.º 10
0
    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"
Ejemplo n.º 11
0
def obtain_accesstoken(tenantname,clientid,clientsecret):
    auth_context = AuthenticationContext('https://login.microsoftonline.com/' +
        tenantname)
    token = auth_context.acquire_token_with_client_credentials(
        resource="https://graph.microsoft.com",client_id=clientid,
        client_secret=clientsecret)
    return token
Ejemplo n.º 12
0
 def _get_token(self):
     context = AuthenticationContext(self.authority_uri)
     code = context.acquire_user_code(self.client_uri, self.client_id)
     _prompt_for_code(code)
     self.config_data = context.acquire_token_with_device_code(
         self.client_uri, code, self.client_id)
     self._cache_creds()
Ejemplo n.º 13
0
def get_client(cluster):
    """
    get cached, authenticated client for given cluster
    """
    assert isinstance(cluster, str)
    assert cluster.startswith('https')

    global _client_cache
    c = _client_cache.get(cluster)
    if c is None:
        # create new auth context
        ac = AuthenticationContext("https://login.microsoftonline.com/common")
        client_id = NotebookKustoClient.client_id()

        # create parameters
        user_code_info = ac.acquire_user_code(cluster, client_id)

        # ask user to authenticate somehow
        code = user_code_info[OAuth2DeviceCodeResponseParameters.USER_CODE]
        url = user_code_info[
            OAuth2DeviceCodeResponseParameters.VERIFICATION_URL]
        promp_for_aad_device_login(url=url, text='Authenticate', code=code)

        # wait for user to input code
        token = ac.acquire_token_with_device_code(cluster, user_code_info,
                                                  client_id)
        assert token is not None
        _client_cache[cluster] = c = NotebookKustoClient(cluster, ac)

    return c
Ejemplo n.º 14
0
 def _refresh_creds(self):
     context = AuthenticationContext(self.authority_uri)
     self.config_data = context.acquire_token_with_refresh_token(
         self.config_data["refreshToken"], self.client_id, self.client_uri)
     if self.debug:
         print(f"got new token expiring {self.config_data['expiresOn']}")
         self._cache_creds()
Ejemplo n.º 15
0
 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
Ejemplo n.º 16
0
def main_logic():
    code = flask.request.args['code']

    state = flask.request.args['state']

    if state != SESSION.auth_state:
        raise ValueError("State does not match")
    auth_context = AuthenticationContext(AUTHORITY_URL, api_version=None)
    token_response = auth_context.acquire_token_with_authorization_code(
        code, REDIRECT_URI, config.RESOURCE, config.CLIENT_ID,
        config.CLIENT_SECRET)

    SESSION.headers.update({
        'Authorization':
        "Bearer" + token_response['accessToken'],
        'User-Agent':
        'adal-python-sample',
        'Accept':
        'application/json',
        'Content-Type':
        'application/json',
        'return-client-request-id':
        'false'
    })
    '''endpoint = config.RESOURCE + '/' + config.API_VERSION + '/me/findMeetingTimes'''
    endpoint = config.RESOURCE + '/' + config.API_VERSION + '/me/calendars'
    graph_data = SESSION.post(endpoint, stream=False).json()

    print('Session' + str(graph_data))
    return jsonify(graph_data)
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
    def getAccessToken(self) -> Optional[str]:
        context = AuthenticationContext(self.authority)
        token = context.acquire_token_with_client_credentials(
            self.resource, self.app_id, self.app_secret)
        if token and "access_token" in token:
            return token["accessToken"]

        return None
Ejemplo n.º 19
0
def generate_aad_token():
    resource = "https://storage.azure.com/"
    client_secret = "Lky5pTg2teniHdbeTlmOuivjdIPBPcwMQJ49wGwKiXA="
    client_id = "bd8e91da-c58c-4407-95e0-a8ecad012fc7"
    authority_url = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/"
    auth_context = AuthenticationContext(authority_url, api_version=None)
    return auth_context.acquire_token_with_client_credentials(
        resource, client_id, client_secret)
Ejemplo n.º 20
0
def get_token():
    code = request.args['code']
    state = request.args['state']
    if state != session['state']:
        raise ValueError("State does not match")
    auth_context = AuthenticationContext(AUTHORITY_URL)
    token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, app.config['RESOURCE'], app.config['CLIENT_ID'], app.config['CLIENT_SECRET'])
    session['access_token'] = token_response['accessToken']
    return flask.redirect('/graphcall')
    def __do_refresh_token(self):
        auth_context = AuthenticationContext(
            AzureTokenService.authority_url_format.format(self.__tenant_id))
        self.__token = auth_context.acquire_token_with_refresh_token(
            self.__token["refreshToken"], AzureTokenService.client_id,
            AzureTokenService.resource_url)
        self.__credentials = AADTokenCredentials(self.__token,
                                                 AzureTokenService.client_id)

        self.__update_refresh_token_timer()
Ejemplo n.º 22
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')
Ejemplo n.º 23
0
def ensure_tokens(client_id, tokens):
    expiresOn = parser.parse(tokens['expiresOn'])

    if expiresOn < datetime.now() + timedelta(minutes=10):
        ctx = AuthenticationContext(config.AUTHORITY_URL, api_version=None)

        return ctx.acquire_token_with_refresh_token(tokens['refreshToken'],
                                                    client_id, config.RESOURCE)

    return tokens
 def _acquire_token(self):
     parsed = urlparse(self.path)
     code = parse_qs(parsed.query)["code"][0]
     state = parse_qs(parsed.query)["state"][0]
     cookie = Cookie.SimpleCookie(self.headers["Cookie"])
     if state != cookie["auth_state"].value:
         raise ValueError("state does not match")
     auth_context = AuthenticationContext(authority_url)
     return auth_context.acquire_token_with_authorization_code(
         code, REDIRECT_URI, RESOURCE, sample_parameters["clientId"], sample_parameters["clientSecret"]
     )
 def _acquire_token(self):
     parsed = urlparse(self.path)
     code = parse_qs(parsed.query)['code'][0]
     state = parse_qs(parsed.query)['state'][0]
     cookie = Cookie.SimpleCookie(self.headers["Cookie"])
     if state != cookie['auth_state'].value:
         raise ValueError('state does not match')
     auth_context = AuthenticationContext(authority_url)
     return auth_context.acquire_token_with_authorization_code(
         code, REDIRECT_URI, RESOURCE, sample_parameters['clientId'],
         sample_parameters['clientSecret'])
 def _get_token(self):
     """request a valid access token from azure active directory
     """
     auth_context = AuthenticationContext(
         f"{self._settings['microsoft_login']}/{self._settings['tenant_name']}"
     )
     token = auth_context.acquire_token_with_client_credentials(
         resource=self._settings["resource"],
         client_id=self._settings["app_id"],
         client_secret=self._settings["app_secret"])
     self._token = token
Ejemplo n.º 27
0
def refresh_access_token(refresh_token):
    context = AuthenticationContext(authority_url)
    # function link
    token_response = context.acquire_token_with_refresh_token(
        refresh_token, user_parameters['client_id'],
        azure_databricks_resource_id)
    # print all the fields in the token_response
    for key in token_response.keys():
        print(str(key) + ': ' + str(token_response[key]))

    # the new 'refreshToken' and  'accessToken' will be returned
    return (token_response['refreshToken'], token_response['accessToken'])
Ejemplo n.º 28
0
    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)
Ejemplo n.º 29
0
def generate_dataframe_from_table(spark, spark_args, table):
    application_id = spark_args.application_id
    directory_id = spark_args.directory_id
    adb_secret_scope = spark_args.adb_secret_scope_name
    adb_sp_client_key_secret_name = spark_args.adb_sp_client_key_secret_name
    database = spark_args.jdbc_database
    jdbc_host = spark_args.jdbc_host
    jdbc_port = spark_args.jdbc_port
    jdbc_username_key_name = spark_args.jdbc_username_key_name
    jdbc_password_key_name = spark_args.jdbc_password_key_name
    use_msi_azure_sql_auth = spark_args.use_msi_azure_sql_auth

    client_secret = SERVICE_PRINCIPAL_SECRET if SERVICE_PRINCIPAL_SECRET is not None else dbutils.secrets.get(
        scope=adb_secret_scope, key=adb_sp_client_key_secret_name)

    df_constructor = spark.read.format("jdbc") \
        .option("url", f"jdbc:sqlserver://{jdbc_host}:{jdbc_port};databaseName={database};") \
        .option("dbtable", table) \
        .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
        .option("hostNameInCertificate", "*.database.windows.net") \
        .option("encrypt", "true") \
        .option("ServerCertificate", "false") \
        .option("trustServerCertificate", "false") \
        .option("loginTimeout", "30")

    if use_msi_azure_sql_auth:
        sts_url = "https://login.microsoftonline.com/" + directory_id
        auth_context = AuthenticationContext(sts_url)
        token_obj = auth_context.acquire_token_with_client_credentials(
            "https://database.windows.net/", application_id, client_secret)
        access_token = token_obj['accessToken']
        df_constructor.option("accessToken", access_token)
    else:
        service_principal_credential = ClientSecretCredential(
            tenant_id=spark_args.directory_id,
            client_id=spark_args.application_id,
            client_secret=SERVICE_PRINCIPAL_SECRET)
        secret_client = SecretClient(vault_url=spark_args.key_vault_url,
                                     credential=service_principal_credential)

        df_constructor.option(
            "user",
            secret_client.get_secret(name=jdbc_username_key_name).value)
        df_constructor.option(
            "password",
            secret_client.get_secret(name=jdbc_password_key_name).value)

    df = df_constructor.load()
    return df
 def _acquire_token(self):
     parsed = urlparse(self.path)
     code = parse_qs(parsed.query)['code'][0]
     state = parse_qs(parsed.query)['state'][0]
     cookie = Cookie.SimpleCookie(self.headers["Cookie"])
     if state != cookie['auth_state'].value:
         raise ValueError('state does not match')
     ### Main logic begins
     auth_context = AuthenticationContext(authority_url, api_version=None)
     return auth_context.acquire_token_with_authorization_code(
         code,
         REDIRECT_URI,
         RESOURCE,
         sample_parameters['clientId'],
         sample_parameters['clientSecret'])
Ejemplo n.º 31
0
def _aquire_token():
    '''Gets the access_token with authorization code.
    '''
    code = flask.request.args['code']
    state = flask.request.args['state']
    # Main ADAL logic starts.
    auth_context = AuthenticationContext(AUTHORITY_URL)
    token_response = auth_context.acquire_token_with_authorization_code(
        code,
        REDIRECT_URI,
        config.RESOURCE,
        config.CLIENT_ID,
        config.CLIENT_SECRET)

    return token_response
Ejemplo n.º 32
0
 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 do_GET(self):
     if self.path == '/':
         self.send_response(307)
         login_url = 'http://localhost:{}/login'.format(PORT)
         self.send_header('Location', login_url)
         self.end_headers()
     elif self.path == '/login':
         auth_state = (''.join(random.SystemRandom()
                               .choice(string.ascii_uppercase + string.digits)
                               for _ in range(48)))
         cookie = Cookie.SimpleCookie()
         cookie['auth_state'] = auth_state
         authorization_url = TEMPLATE_AUTHZ_URL.format(
             sample_parameters['tenant'],
             sample_parameters['clientId'],
             REDIRECT_URI,
             auth_state,
             RESOURCE)
         self.send_response(307)
         self.send_header('Set-Cookie', cookie.output(header=''))
         self.send_header('Location', authorization_url)
         self.end_headers()
     elif self.path.startswith('/getAToken'):
         is_ok = True
         try:
             token_response = self._acquire_token()
             message = 'response: ' + json.dumps(token_response)
             #Later, if the access token is expired it can be refreshed.
             auth_context = AuthenticationContext(authority_url, api_version=None)
             token_response = auth_context.acquire_token_with_refresh_token(
                 token_response['refreshToken'],
                 sample_parameters['clientId'],
                 RESOURCE,
                 sample_parameters['clientSecret'])
             message = (message + '*** And here is the refresh response:' +
                        json.dumps(token_response))
         except ValueError as exp:
             message = str(exp)
             is_ok = False
         self._send_response(message, is_ok)
 def do_GET(self):
     if self.path == "/":
         self.send_response(307)
         login_url = "http://localhost:{}/login".format(PORT)
         self.send_header("Location", login_url)
         self.end_headers()
     elif self.path == "/login":
         auth_state = "".join(
             random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(48)
         )
         cookie = Cookie.SimpleCookie()
         cookie["auth_state"] = auth_state
         authorization_url = TEMPLATE_AUTHZ_URL.format(
             sample_parameters["tenant"], sample_parameters["clientId"], REDIRECT_URI, auth_state, RESOURCE
         )
         self.send_response(307)
         self.send_header("Set-Cookie", cookie.output(header=""))
         self.send_header("Location", authorization_url)
         self.end_headers()
     elif self.path.startswith("/getAToken"):
         is_ok = True
         try:
             token_response = self._acquire_token()
             message = "response: " + json.dumps(token_response)
             # Later, if the access token is expired it can be refreshed.
             auth_context = AuthenticationContext(authority_url)
             token_response = auth_context.acquire_token_with_refresh_token(
                 token_response["refreshToken"],
                 sample_parameters["clientId"],
                 RESOURCE,
                 sample_parameters["clientSecret"],
             )
             message = message + "*** And here is the refresh response:" + json.dumps(token_response)
         except ValueError as exp:
             message = str(exp)
             is_ok = False
         self._send_response(message, is_ok)