Azure AD Python - Unexpected polling state invalid_client error - azure

store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 273, in acquire_token_with_device_code
return self._acquire_token(token_func)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/authentication_context.py", line 266, in token_func
token = token_request.get_token_with_device_code(user_code_info)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/token_request.py", line 398, in get_token_with_device_code
token = client.get_token_with_polling(oauth_parameters, interval, expires_in)
File "/Users/jyao/Desktop/azureblobtest/lib/python3.7/site-packages/adal/oauth2_client.py", line 345, in get_token_with_polling
wire_response)
adal.adal_error.AdalError: Unexpected polling state invalid_client
How could I get rid of this error after input the device code and sign-in successfully.
steps:
From a python interactive prompt, run this code [1] (All modules are already loaded). Where:
authority_url = 'https://login.microsoftonline.com/my_tenant_id'
resource_uri = "https://storage.azure.com/"
context = adal.AuthenticationContext(authority_uri)
code = context.acquire_user_code(resource_uri, client_id)
print(code['message'])
store_token = context.acquire_token_with_device_code(resource_uri, code, client_id)
credentials = AADTokenCredentials(store_token, client_id)
2.Open the URL https://microsoft.com/devicelogin in a browser.
3.Enter the code E8B2DVT67
4.Confirm the application's name, it is correct.
5.Authenticate using the user's credentials.
6.Get a message in browser saying "You have signed in to the TEST-APP application on your device. You may now close this window."
7.Get the error shown in my previous message in the python interactive prompt.
I use a native app and update manifest and set "allowPublicClient": true permission.

Your code works fine.
If we set allowPublicClient:false, we will encounter this error.
After updating allowPublicClient to true, it will work. Note: There will be some delay for the configuration to take effect.

Related

AWS secret manager time out sometimes

I am fetching a secret from secret manager on a lambda. The request fails sometimes. Which is totally strange, it is working fine and couple of hours later I check and I am getting time out.
def get_credentials(self):
"""Retrieve credentials from the Secrets Manager service."""
boto_config = BotoConfig(connect_timeout=3, retries={"max_attempts": 3})
secrets_client = self.boto_session.client(
service_name="secretsmanager",
region_name=self.boto_session.region_name,
config=boto_config,
)
secret_value = secrets_client.get_secret_value(SecretId=self._secret_name)
secret = secret_value["SecretString"]
I try to debug the lambda and later seems to be working again, without any change, those state changes happen in hours. Any hint why that could happen?
Traceback (most recent call last):
File "/opt/python/botocore/endpoint.py", line 249, in _do_get_response
http_response = self._send(request)
File "/opt/python/botocore/endpoint.py", line 321, in _send
return self.http_session.send(request)
File "/opt/python/botocore/httpsession.py", line 438, in send
raise ConnectTimeoutError(endpoint_url=request.url, error=e)
botocore.exceptions.ConnectTimeoutError: Connect timeout on endpoint URL: "https://secretsmanager.eu-central-1.amazonaws.com/"
You are using the legacy retry mode (is the default one in boto3), which has very limited functionality as it only works for a very limited number of errors.
You should try changing your retry strategy to something like Standard retry mode or Adaptative. In that case your code would look like:
from botocore.config import Config as BotoConfig
boto_config = BotoConfig(
connect_timeout=3,
retries={
"max_attempts": 3,
"mode":"standard"
}
)
secrets_client = self.boto_session.client(
service_name="secretsmanager",
region_name=self.boto_session.region_name,
config=boto_config,
)

Snowflake connector.connect breaks with an error message that tells me nothing

I installed the snowflake connector via the command: pip3 install snowflake-connector-python[pandas]==2.3.3 asn1crypto==1.3.0 --user
I attempted to connect via:
from snowflake import connector
con = connector.connect(
host='.snowflakecomputing.com',
user='THE USER I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
password='THE PASSWORD I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
account='zka81761.us-east-1',
warehouse='COMPUTE_WH',
database='DEMO_DB',
schema='PUBLIC',
protocol='https',
port=443)
When executing the above code it just hangs for several minutes then I get an error:
snowflake.connector.errors.OperationalError: 250003: Failed to execute request: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
The longer version is:
File "tests/integration_tests/data_sources/test_snowflake_ds.py", line 6, in test_snowflake_ds
ds = SnowflakeDS(query='SELECT * FROM HEALTHCARE_COSTS', host='.snowflakecomputing.com', user='GEORGE3D6', password='a passwordd', account='zka81761.us-east-1', warehouse='COMPUTE_WH', database='DEMO_DB', schema='PUBLIC', protocol='https', port=443)
File "/home/george/mindsdb_native/mindsdb_native/libs/data_types/data_source.py", line 13, in __init__
df, col_map = self._setup(*args, **kwargs)
File "/home/george/mindsdb_native/mindsdb_native/libs/data_sources/snowflake_ds.py", line 21, in _setup
port=port)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/__init__.py", line 52, in Connect
return SnowflakeConnection(**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 219, in __init__
self.connect(**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 414, in connect
self.__open_connection()
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 613, in __open_connection
self._authenticate(auth_instance)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 839, in _authenticate
self.__authenticate(self.__preprocess_auth_instance(auth_instance))
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/connection.py", line 869, in __authenticate
session_parameters=self._session_parameters,
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/auth.py", line 209, in authenticate
socket_timeout=self._rest._connection.login_timeout)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 509, in _post_request
_include_retry_params=_include_retry_params)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 586, in fetch
**kwargs)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 676, in _request_exec_wrapper
conn, full_url, cause)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/network.py", line 706, in handle_invalid_certificate_error
'errno': ER_FAILED_TO_REQUEST,
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/errors.py", line 128, in errorhandler_wrapper
connection.errorhandler(connection, cursor, error_class, error_value)
File "/home/george/.local/lib/python3.7/site-packages/snowflake/connector/errors.py", line 90, in default_errorhandler
done_format_msg=error_value.get('done_format_msg'))
snowflake.connector.errors.OperationalError: 250003: Failed to execute request: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
This error message tells me nothing, any help would be appreicated
According to the documentation on the python API the host field is no longer used so try removing that. Also, even if it was used, you haven't enclosed it properly in quotes:
You have: host='.snowflakecomputing.com,
Should be: host='.snowflakecomputing.com',
First, I'd see if removing the host completely fixes your issue since it shouldn't be used anyway.
Googling the error, and the error message itself, suggests that the issue is due to the URL being too long so I'd say the error is down to the fact that you haven't enclosed it properly.
I used to connect snowflake from python like below:
import snowflake.connector as sf
sfconnection = sf.connect(
user='THE USER I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
password='THE PASSWORD I USE FOR LOGGING IN TO MY TRIAL ACCOUNT',
account='zka81761.us-east-1',
warehouse='COMPUTE_WH',
database='DEMO_DB',
schema='PUBLIC')
Apparently the docs are wrong and the host should now be the full URL (so, in my case zka81761.us-east-1.snowflakecomputing.com). That is to say, it should include the account.

Trouble sending a batch create entity request in dialogflow

I have defined the following function. The purpose is to make batch create entity request with dialogflow client. I am using this method after sending many individual tests did not scale well.
The problem seems to be the line that defines EntityType. Seems like "entityType" is not valid but that is what is in the dialogflow v2 documentation which is the current version I am using.
Any ideas on what the issue is?
def create_batch_entity_types(self):
client = self.get_entity_client()
print(DialogFlowClient.batch_list)
EntityType = {
"entityTypes": DialogFlowClient.batch_list
}
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
def callback(operation_future):
# Handle result.
result = operation_future.result()
print(result)
response.add_done_callback(callback)
After running the function I received this error
Traceback (most recent call last):
File "df_client.py", line 540, in <module>
create_entity_types_from_database()
File "df_client.py", line 426, in create_entity_types_from_database
df.create_batch_entity_types()
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/dialogflow/dialogflow_accessor.py", line 99, in create_batch_entity_types
response = client.batch_update_entity_types(parent=AGENT_PATH, entity_type_batch_inline=EntityType)
File "/Users/andrewflorial/Documents/PROJECTS/curlbot/venv/lib/python3.7/site-packages/dialogflow_v2/gapic/entity_types_client.py", line 767, in batch_update_entity_types
update_mask=update_mask,
ValueError: Protocol message EntityTypeBatch has no "entityTypes" field.
The argument for entity_type_batch_inline must have the same form as EntityTypeBatch.
Look how that type looks like: https://dialogflow-python-client-v2.readthedocs.io/en/latest/gapic/v2/types.html#dialogflow_v2.types.EntityTypeBatch
It has to have entity_types field, not entityTypes.

read mails from custom label in gmail using python(google api)

I want to read mail from customed label USING PYTHON and google API.However i m getting error of change the label from inbox to customed label
label_id_one = 'AW'
label_id_two = 'UNREAD'
unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one, label_id_two]).execute()
GETTING THIS ERROR:
File "C:\Users\AppData\Local\Programs\Python\Python36-32\lib\site-packages\googleapiclient\discovery.py", line 272, in _retrieve_discovery_doc
raise HttpError(resp, content, uri=actual_url)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://gmail.googleapis.com/$discovery/rest?version=v2 returned "The request cannot be identified with a project. Please pass a valid API key with the request.">
I have removed labelIDs and added q parameter as shown below. Here the "test" is the folder created by me in Gmail.
unread_msgs = GMAIL.users().messages().list(userId='me',q='in:test is:unread').execute()

python3 exchangelib credentials

Im trying to log into an exchangeserver with the exchangelib.
When I try to run the script it gives me an error:
File "/usr/local/lib/python3.5/dist-packages/exchangelib/protocol.py", line 61, in init
assert isinstance(credentials, Credentials)
AssertionError
From what I can understand it says my credential variabel is not of the right type. I have tried both with and without autodiscover enabled. I get the same error.
Here is the relevant code.
credents = Credentials(username='domain\\aaa.fh', password= 'password'),
config = Configuration(server='domain.aaa.no', credentials= credents)
account = Account(
primary_smtp_address='fh#domain.no',
config=config,
autodiscover=True,
access_type=DELEGATE)
Try this way:
config = Configuration(
server='mail.example.com',
credentials=Credentials(username='Domain\username', password='password'),
auth_type=NTLM
)
account = Account(primary_smtp_address='Emailaddress#domain.com', config=config,
access_type=DELEGATE)
This is due to the dreaded Python trailing comma in the first line, which "helpfully" turns your credents variable into a tuple of Credentials.

Resources