azuread / azure-activedirectory-library-for-python Goto Github PK
View Code? Open in Web Editor NEWADAL for Python
Home Page: http://adal-python.readthedocs.io
License: Other
ADAL for Python
Home Page: http://adal-python.readthedocs.io
License: Other
how to develop for Multi-Factor Authentication , I can not find any development document in offical website , so I want to ask whether microsoft offer some technical document to develop for Multi-Factor Authentication account?
Hi,
Line 34 and 110 has outdated links.
Might be more faulty links...
A new trusted authority host login.microsoftonline.us
has been deployed, and we need to add it into our code base.
It would be helpful to be able to identify which apps have which version of ADAL so that we can identify apps that should be updated.
Do not implement this until we have agreement on the shape of the public API changes.
I'd like to share that a problem that can't be authorized using id(MSA) and password. In fact, It's a bit ambiguous to tell this to Azure Cli project or to ADAL python project. But since the Azure cli is build on ADAL python. I think it's more appropriate to write here.
It's horrible for the customer couldn't login with own id (MSA) and password when trying to access Azure CLI. This is very natural with PowerShell
Becuase of that. I have tried to drill down what's going on. and I share it.
I really hope that below information could be helpful to fix this problem(?), anyway.
Additionally, some of respose of it, "not recommended", I guess the most of people might want to know why is not recommended. just "not recommended" is not enough to answer.
BTW, When I tried to login with MSA and password, error call stack is like below.
Mex._select_username_password_polices in mex line 134 Python
Mex._parse in mex line 251 Python
Mex.discover in mex line 104 Python
TokenRequest._get_token_username_password_federated in token_request line 238 Python
TokenRequest.get_token_with_username_password in token_request line 286 Python
token_func in AuthenticationContext.acquire_token_with_username_password in authentication_context line 143 Python
AuthenticationContext._acquire_token in authentication_context line 109 Python
AuthenticationContext.acquire_token_with_username_password in authentication_context line 145 Python
SubscriptionFinder.find_from_user_account in _profile line 333 Python
Profile.find_subscriptions_on_login in _profile line 121 Python
login in custom line 70 Python
_execute_command in create_command in init line 333 Python
Application.execute in application line 157 Python
main in main line 37 Python
main module line 23 Python
I found that exception originate is select_username_password_polices() function
def _select_username_password_polices(self, xpath):
policies = {}
// xpath = 'wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10'
username_token_nodes = xmlutil.xpath_find(self._dom, xpath) // couln't find user token information
if not username_token_nodes:
self._log.warn("No username token policy nodes found.")
return
...
This is below log information as i tested
Command arguments ['login', '-u', '[email protected]']
Loading all installed modules as module with name 'login' not found.
Installed command modules ['acr', 'acs', 'appservice', 'cloud', 'component', 'configure', 'container', 'context', 'feedback', 'network', 'profile', 'resource', 'role', 'storage', 'vm']
Registered application event handler 'CommandTableParams.Loaded' at <function add_id_parameters at 0x03E176F0>
Registered application event handler 'CommandTable.Loaded' at <function add_id_parameters at 0x03E176F0>
...
Loaded all modules in 6.903 seconds. (note: there's always an overhead with the first module loaded)
Application event 'CommandTable.Loaded' with event data {'command_table': OrderedDict([('provider register', <azure.cli.core.commands.CliCommand object at 0x04D3E5D0>), ('network traffic-manager endpoint list', <azure.cli.core.commands.CliCommand object at 0x04CFEFF0>), ('network application-gateway ssl-cert list', <azure.cli.core.commands.CliCommand object at 0x0446C850>), ('network vnet-gateway reset', <azure.cli.core.commands.CliCommand object at 0x04CE70F0>), ('network vnet peering update', <azure.cli.core.commands.CliCommand object at 0x04 [...]
Application event 'CommandParser.Loaded' with event data {'parser': AzCliCommandParser(prog='az', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)}
Application event 'CommandTableParams.Loaded' with event data {'command_table': OrderedDict([('provider register', <azure.cli.core.commands.CliCommand object at 0x04D3E5D0>), ('network traffic-manager endpoint list', <azure.cli.core.commands.CliCommand object at 0x04CFEFF0>), ('network application-gateway ssl-cert list', <azure.cli.core.commands.CliCommand object at 0x0446C850>), ('network vnet-gateway reset', <azure.cli.core.commands.CliCommand object at 0x04CE70F0>), ('network vnet peering update', <azure.cli.core.commands.CliCommand object at 0x04 [...]
Application event 'CommandParser.Parsed' with event data {'args': Namespace(_command_package='login', _jmespath_query=None, _log_verbosity_debug=False, _log_verbosity_verbose=False, _output_format='json', _parser=AzCliCommandParser(prog='az login', usage=None, description='Log in to access Azure subscriptions', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True), _validators=[], command='login', func=<function create_command.._execute_command at 0x04D2B1E0>, password=None, service_principal=None, te [...]
Password:
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - Authority:Performing instance discovery: https://login.microsoftonline.com/common
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - Authority:Performing static instance discovery
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - Authority:Authority validated via static instance discovery
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - TokenRequest:Acquiring token with username password.
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - OAuth2Client:finding with query: {"userId": "[email protected]", "_clientId": "04b07795-8ddb-461a-bbee-02f9e1bf7b46"}
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - OAuth2Client:Looking for potential cache entries:
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - OAuth2Client:{"userId": "[email protected]", "_clientId": "04b07795-8ddb-461a-bbee-02f9e1bf7b46"}
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - OAuth2Client:Found 0 potential entries.
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm:Performing user realm discovery at: https://login.microsoftonline.com/common/UserRealm/himskim%40msn.com?api-version=1.0
requests.packages.urllib3.connectionpool : Starting new HTTPS connection (1): login.microsoftonline.com
requests.packages.urllib3.connectionpool : https://login.microsoftonline.com:443 "GET /common/UserRealm/himskim%40msn.com?api-version=1.0 HTTP/1.1" 200 363
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm:User Realm Discovery Server returned this correlation_id: 532b43b3-a5b1-4443-a0a0-f3a563efc576
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm:Discovery response:
{"ver":"1.0","account_type":"Federated","domain_name":"live.com","federation_protocol":"WSTrust","federation_metadata_url":"https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml","federation_active_auth_url":"https://login.live.com/rst2.srf","cloud_instance_name":"microsoftonline.com","cloud_audience_urn":"urn:federation:MicrosoftOnline"}
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm:UserRealm response:
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm: AccountType: federated
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm: FederationProtocol: wstrust
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm: FederationMetatdataUrl: https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - UserRealm: FederationActiveAuthUrl: https://login.live.com/rst2.srf
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - TokenRequest:Acquiring token with username password for federated user
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - TokenRequest:Attempting mex at: https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - MEX:Mex created with url: https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - MEX:Retrieving mex at: https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml
requests.packages.urllib3.connectionpool : Starting new HTTPS connection (1): nexus.passport.com
requests.packages.urllib3.connectionpool : https://nexus.passport.com:443 "GET /FederationMetadata/2007-06/FederationMetadata.xml HTTP/1.1" 200 2980
adal-python : 532b43b3-a5b1-4443-a0a0-f3a563efc576 - MEX:No username token policy nodes found.
Thanks.
myung
The get_token_with_authorization_code function should also return the id_token along with the access_token as described in https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-protocols-oauth-code/
If i'm not mistaken, currently, it only returns an access_token and refresh_token.
In the case the STS returns back an error with an extra parameter, is it accessible to the developer. For instance:
error=interaction_required
error_description=AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '<Web API App/Client ID>'.
claims={"access_token":{"polids":{"essential":true,"Values":["<GUID>"]}}}
There is no timeout set on the requests.post()
call in this function on line 147. This manifests as occasional infinite hangs for us in our scripts when the upstream server has problems.
I am having issues authenticating to the Dynamics 365 CRM Web API via the Python ADAL library. Particularly, the acquire_token_with_username_password function. I can't seem to acquire an access token. Full error message below.
The only "wrinkle" in my configuration is that our Azure AD is federated with an on-prem AD. Also, authentication seems to work using a device code & interactive login via the acquire_token_with_device_code function. The problem is I am writing a console application that is intended to be non-interactive.
Has anyone else encountered this issue, or could otherwise explain how to resolve it?
adal.adal_error.AdalError: Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS70002: Error validating credentials. AADSTS50008: SAML token is invalid. AADSTS50006: The element with ID '_011236b3-e879-4bb5-b640-86577dda2a0a' was either unsigned or the signature was invalid.\r\nTrace ID: 7b0fbeae-5a37-42bd-af63-f1decf720926\r\nCorrelation ID: 3242f1a3-41be-49f3-ab2c-b643625b8d5b\r\nTimestamp: 2017-03-13 02:34:41Z","error_codes":[70002,50008,50006],"timestamp":"2017-03-13 02:34:41Z","trace_id":"7b0fbeae-5a37-42bd-af63-f1decf720926","correlation_id":"3242f1a3-41be-49f3-ab2c-b643625b8d5b"}
We're looking to authenticate an App Service to the other Azure APIs (e.g. Key Vault). Is it possible to use the AADL library with the new Managed Service Identities feature?
https://docs.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity
It looks like it's probably not available yet? https://docs.microsoft.com/en-us/azure/active-directory/msi-known-issues#does-msi-work-with-the-active-directory-authentication-library-adal-or-the-microsoft-authentication-library-msal
Hi,
we stumbled over what we think can be categorized as a bug in the library. We are able to successfully obtain a token for a given resource and client id. However, the token does not grant us access to the resource. Whenever we call the resource with the access_token
, we get a HTTP 401 response.
When we use the .Net library, with the exact same parameters, the token works.
The difference we have found is that the python library explicitly sends the parameter api-version=1.0
to the oauth2 endpoint.
POST https://login.microsoftonline.com/common/oauth2/token?api-version=1.0
Once we changed the following line in oauth2_client.py
in the adal library, I could access my resource.
return urlparse('{}?{}'.format(self._token_endpoint, urlencode(parameters)))
in the method _create_token_url
, to
return urlparse(self._token_endpoint)
.
See also this question on StackOverflow, the latest answer is from us.
http://stackoverflow.com/questions/37909332/401-unauthorized-making-rest-call-to-azure-api-app-using-bearer-token/
Whyย am I getting an authentication_context.py:88: DeprecationWarning even when calling:
context = adal.AuthenticationContext((authentication_endpoint + tenant_id, api_version=None))
I am working on a Dynamics CRM integration for a client. I wasn't involved in the setup of the CRM but from poking around they seem to have their own sts server setup at
https://sts.orgname.org/
And I can access the normal login page at https://sts.orgname.org/adsf/ls/
.
If I use https://sts.orgname.org/
as the AUTHORIZATION_URL
I get the error
Authority: ERROR: Instance Discovery request failed
I get this error no matter if I include /adsf/ls/
or not. Is there an magic AUTHORIZATION_URL
equivalent I can derive from https://sts.orgname.org
?
I can definitely provide more information and context if it is required. There maybe documentation which addresses this question but it has proved challenging to find.
This library currently uses INFO level for some log messages which I would consider DEBUG level like below. This produces a lot of noise when setting the root logger to INFO in an application. I would suggest that for the messages below the DEBUG level is used.
18:39:54 adal-python 140073437169408 INFO 706dfbee-36cf... - TokenRequest:Getting token from cache with refresh if necessary.
18:39:54 adal-python 140073437169408 INFO 9a95f211-4224... - TokenRequest:Acquiring token with username password.
18:39:54 adal-python 140073437169408 INFO 9a95f211-4224... - UserRealm:User Realm Discovery Server returned this correlation_id: 9a95f211-4224...
18:39:55 adal-python 140073437169408 INFO 9a95f211-4224... - WSTrustRequest:WS-Trust RST Server returned this correlation_id: 9a95f211-4224...
18:39:55 adal-python 140073437169408 INFO 9a95f211-4224... - WSTrustResponse:Found token of type: urn:oasis:names:tc:SAML:1.0:assertion
18:39:56 adal-python 140073437169408 INFO 9a95f211-4224... - OAuth2Client:Get Token Server returned this correlation_id: 9a95f211-4224...
By this library I am able to fetch access token via client credentials method.
When I am using that token to fetch data from APIM wrapper, the result responded with "status 200" OK but inside content it has "no values". The same resource responds with plenty of data when called from postman.
I just upgraded from 0.1.0 to 0.3.0. I was able to get a token like this:
adal.acquire_token_with_username_password(
'url',
'username',
'password
)
Can I not use this library to get a token using username/password anymore?
I am trying to obtain an access token with client credentials.
I am trying to figure out how to pass the proxy information.
This is the code I am using
context = adal.AuthenticationContext(authority_url)
token = context.acquire_token_with_client_credentials(resource, client_id, client_secret)
print(token['accessToken'])
Hey good work but would be even better with async support instead of blocking calls (I'm not talking about starting another thread / process but genuine async IO support), is there any plan in that regard (using grequests instead of requests for example)?
Right now the version number are repeated in two separated files, so that during each release, we will need to remember to update those 2 occurrences. Actually we can let one of them to reference the other, therefore solving this problem. A pull request for this is on the way.
I've followed the refresh_token sample provided, below are an extract of my code:
context = adal.AuthenticationContext(authority=(authority + tenant_id), validate_authority=False)
token = context.acquire_token_with_client_credentials(resource_id, client_id, client_secret)
print(token)
refresh_token = token['accessToken']
print(refresh_token)
token = context.acquire_token_with_refresh_token(refresh_token, client_id, resource_id)
Firstly command refresh_token = token['refreshToken'] fail, I assume you meant 'accessToken' ?
Last command fail with below:
AdalError: Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS70000: Transmission data parser failure: Refresh Token is malformed or invalid.\r\nTrace ID: 52e91e1c-6ee0-40b8-b3f8-546b8be4fbad\r\nCorrelation ID: 6e9b6654-a911-44f3-9f40-f26555f4df30\r\nTimestamp: 2017-03-15 14:08:19Z","error_codes":[70000],"timestamp":"2017-03-15 14:08:19Z","trace_id":"52e91e1c-6ee0-40b8-b3f8-546b8be4fbad","correlation_id":"6e9b6654-a911-44f3-9f40-f26555f4df30"}
How to correct this error ?
What should I enter in these parameters exactly ? Below is what I used
"resource": "'https://management.core.windows.net", - is this default correct to use ?
"tenant" : I entered the tenant id from app in active directory ?
authorityHostUrl" : "https://login.microsoftonline.com" - is this correct to use ?
In the context of using the PowerBI API, I've been testing token aquistion in the .NET library, using the following code:
var result = true;
var credential = new UserPasswordCredential(username, password);
var authenticationContext = new AuthenticationContext(_authorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(_resourceUrl, clientId, credential);
if (authenticationResult == null)
{
result = false;
}
I am able to get a token perfectly and interact with the PowerBI API perfectly. Works great!
I've noticed that during these calls in HttpClientWrapper there are 3 requests. GET (auth discovery), GET (something else) and POST(token request).
The final POST is attempting to request at the following URI:
https://login.microsoftonline.com/common/oauth2/token
However, when I try and use the python library with the following snippet:
context = adal.AuthenticationContext(authority=self.authority_url, validate_authority=True)
token = context.acquire_token_with_username_password(
resource=self.resource_url, client_id=self.client_id,
username=the_username, password=the_password)
There are only 2 requests. GET(something else), POST(token request). The final POST 404's. The discovery step is missing, and it's performing static discovery.
The final POST is attempting to request at the following URI: https://login.windows.net/common/oauth2/authorize/oauth2/token
I have tried with validate_authority=True and False.
Here are the provided URLs:
authority_url = 'https://login.windows.net/common/oauth2/authorize'
It seems that the urls finally being used for requests are not the same - perhaps its something worth looking at?
I am trying to get access token via acquire_token_with_username_password
in python 2.7, but I get the following issue:
File "E:\Projects\python\adal\adal_test.py", line 8, in <module>
'994e5ec6-28f2-45b3-a892-c9131b266a05')
File "E:\Projects\python\adal\adal\authentication_context.py", line 125, in acquire_token_with_username_password
return self._acquire_token(token_func)
File "E:\Projects\python\adal\adal\authentication_context.py", line 89, in _acquire_token
return token_func(self)
File "E:\Projects\python\adal\adal\authentication_context.py", line 123, in token_func
return token_request.get_token_with_username_password(username, password)
File "E:\Projects\python\adal\adal\token_request.py", line 265, in get_token_with_username_password
token = self._get_token_username_password_federated(username, password)
File "E:\Projects\python\adal\adal\token_request.py", line 243, in _get_token_username_password_federated
username, password)
File "E:\Projects\python\adal\adal\token_request.py", line 210, in _perform_username_password_for_access_token_exchange
return self._perform_wstrust_assertion_oauth_exchange(wstrust_response)
File "E:\Projects\python\adal\adal\token_request.py", line 182, in _perform_wstrust_assertion_oauth_exchange
grant_type = _get_saml_grant_type(wstrust_response)
File "E:\Projects\python\adal\adal\token_request.py", line 55, in _get_saml_grant_type
token_type = wstrust_response.token_type
AttributeError: 'NoneType' object has no attribute 'token_type'
And my code snippet is like:
import adal
context = adal.AuthenticationContext('https://login.microsoftonline.com/<tenantID>')
RESOURCE = '00000002-0000-0000-c000-000000000000' #AAD graph resource
token = context.acquire_token_with_username_password(
RESOURCE,
'username',
'paddword',
'aad_clientId')
print token
refresh_token = token['refreshToken']
I cannot figure out why. Could you help me to fix it.
Installing the Disk encryption extension on a stock Ubuntu server fails with an error on pip install adal
Azure VM image details:
"publisher": "Canonical",
"offer": "UbuntuServer",
"sku": "16.04-LTS",
"version": "latest"
Error from Boot Diagnostics:
[AzureDiskEncryption] 3386: [Info] Executing: lvs --noheadings --nameprefixes --unquoted -o lv_name,vg_name,lv_kernel_major,lv_kernel_minor
[AzureDiskEncryption] 3386: [Info] Installing pre-requisites
[AzureDiskEncryption] 3386: [Info] Executing: apt-get update
[AzureDiskEncryption] 3386: [Info] Executing: apt-get install -y at cryptsetup-bin lsscsi python-six python-parted procps psmisc gcc libssl-dev libffi-dev python-dev python-pip
[AzureDiskEncryption] 3386: [Info] Executing: pip install adal
[AzureDiskEncryption] 3386: [Info] Command pip install adal failed with return code 2
stdout:
Collecting adal
stderr:
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 328, in run
wb.build(autobuilding=True)
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 748, in build
self.requirement_set.prepare_files(self.finder)
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 360, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
finder, self.upgrade, require_hashes)
File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 273, in populate_link
self.link = finder.find_requirement(self, upgrade)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 442, in find_requirement
all_candidates = self.find_all_candidates(req.name)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 400, in find_all_candidates
for page in self._get_pages(url_locations, project_name):
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 545, in _get_pages
page = self._get_page(location)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 648, in _get_page
return HTMLPage.get_page(link, session=self.session)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 757, in get_page
"Cache-Control": "max-age=600",
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 378, in request
return super(PipSession, self).request(method, url, *args, **kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 46, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 376, in send
timeout=timeout
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 610, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 228, in increment
total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
2017/12/05 18:20:35.923851 INFO Event: name=Microsoft.Azure.Security.Edp.AzureDiskEncryptionForLinux, op=Install, message=Launch command succeeded: main/handle.py -install, duration=0
2017/12/05 18:20:35.951713 INFO [Microsoft.Azure.Security.Edp.AzureDiskEncryptionForLinux-0.1.0.999308] Enable extension [main/handle.py -enable]
[AzureDiskEncryption] 20356: [Info] Enabling extension
Hi @yugangw-msft,
Look at this:
msrestazure.azure_exceptions.CloudError: Azure Error: InvalidAuthenticationTokenAudience
Message: The access token has been obtained from wrong audience or resource 'https://management.core.windows.net'. It should exactly match (including forward slash) with one of the allowed audiences 'https://management.core.windows.net/','https://management.azure.com/'.
Why are you so nervous to also include the forward slash?
This raises also the question, what about connecting to not public azure?
In #58 I see you added requests != 2.12
to the requirements of adal
. This is sadly not a workable restriction in practice due to the way pip currently does version dependency resolution. To illustrate, consider this simple Python package setup.py:
from setuptools import setup, find_packages
version = '0.1'
setup(
name='depfail',
version=version,
packages=find_packages(),
entry_points={
'console_scripts': [
'run-me = depfail:fail',
]
},
install_requires=[
'requests[security]',
'adal',
],
)
We'll also have a depfail/__init__.py
that looks like this:
def fail():
print("No failure!")
This package has two dependencies, requests[security]
and adal
. You might rationally think that pip would recursively look through dependencies to build a full set of requirements and then use something like a SAT solver to satisfy the constraints imposed on individual packages (and, of course, fail if it can't satisfy them). Unfortunately, that is not the case. In reality here's what your virtualenv will look like if you do pip install .
:
adal (0.4.3)
cffi (1.9.1)
cryptography (1.6)
depfail (0.1)
enum34 (1.1.6)
idna (2.1)
ipaddress (1.0.17)
pip (9.0.1)
pyasn1 (0.1.9)
pycparser (2.17)
PyJWT (1.4.2)
pyOpenSSL (16.2.0)
python-dateutil (2.6.0)
requests (2.12.3)
setuptools (30.2.0)
six (1.10.0)
wheel (0.30.0a0)
As you can see, requests 2.12.3 is installed despite the explicit != 2.12
. Of course if we do a python -c 'import depfail;depfail.fail()'
we get No failure!
. So what's the problem?
Well, when you define a console_script it uses setuptools entry points to invoke your script. The installed script is available in your PATH and looks something like this:
# EASY-INSTALL-ENTRY-SCRIPT: 'depfail==0.1','console_scripts','run-me'
__requires__ = 'depfail==0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('depfail==0.1', 'console_scripts', 'run-me')()
)
load_entry_point
is a bit more conscientious about whether or not dependencies are satisfied so it proceeds to check to see if adal's requirements are met and...
pkg_resources.ContextualVersionConflict: (requests 2.12.3 (/path/to/lib/python2.7/site-packages/requests-2.12.3-py2.7.egg), Requirement.parse('requests!=2.12.*,>=2.0.0'), set(['adal']))
This interaction means that adal
can't effectively block requests 2.12 for users who have requests listed as a dependency that is processed before adal
(a presumably common scenario). Additionally, this directive causes major breakage for users who invoke their application via console scripts (not an uncommon path).
It's not obvious from the code/tests if it works at all.
Thanks for maintaining this library - it's helping me connect our internal app to Azure AD.
@yugangw-msft When will the dev branch get merged to master? Just wondering how long I'll have to maintain a workaround for the str
/unicode
fix on Python 2.7.
Getting this error:
E Failed: Get Token request returned http error: 401 and server response: {"error":"invalid_client","error_description":"AADSTS70002: Error validating credentials. AADSTS50012: Client assertion audience claim does not match Realm issuer.\r\nTrace ID: b3a77dbe-af3b-4545-8c2c-a76ab79c15ff\r\nCorrelation ID: 5018bf95-777c-448c-96ea-19e2532cbb48\r\nTimestamp: 2017-03-08 23:18:59Z","error_codes":[70002,50012],"timestamp":"2017-03-08 23:18:59Z","trace_id":"b3a77dbe-af3b-4545-8c2c-a76ab79c15ff","correlation_id":"5018bf95-777c-448c-96ea-19e2532cbb48"}
What does this error mean?
code looks like:
key_contents = get_contents(key)
thumbprint = kf.get_private_rsa_fingerprint(key)
token_response = context.acquire_token_with_client_certificate(
kusto_cluster,
client_id,
key_contents,
thumbprint
)
If I use similar params, but use client_secret, it works fine:
token_response = context.acquire_token_with_client_credentials(
kusto_cluster,
client_id,
client_secret)
C# SDK supports PromptBehavior when calling AcquireTokenAsync. Nice to have it in Python as well. With this, it will have a nice way to support MFA. Right now we have to use code flow instead.
This request is to address this issue.
#101
Please add support for MFA to allow customers to automate deployments of MFA. At the moment, it seems Microsoft only supports MFA automation via Powershell.
https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/6998686-update-the-azure-active-directory-powershell-modul
http://connect.microsoft.com/site1164/content/content.aspx?ContentID=32016
A new PR is on the way. Stay tuned.
latest acquire_token_with_username_password with username/password requires client_id parameter. One of our customer is questioning why client_id is not required when they login with az cli. Actually they don't have client id, they're using domain account as username/password to do auth. Given client_id in az cli is open one, there's no way to prevent user from using it. 2 questions here:
previously user use UserPassCredential do auth:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
UserPassCredentials('[email protected]', password)
I can't tell exactly what is going on, but when I add 'adal' to my requirements.txt file in Azure Web App, it bombs out on the 'adal' install with the following:
File "D:\home\site\wwwroot\env\lib\site-packages\pip\_vendor\pkg_resources.py", line 2583, in scan_list
"Expected ',' or end-of-list in",line,"at",line[p:]
ValueError: ("Expected ',' or end-of-list in", 'requests >=2.0.0,!=2.12.*', 'at', '*')
Hello -
I've been struggling to retrieve a token using the acquire_token_with_client_certificate function. No matter what I use for my PEM encoded key / cert, I receive the below error:
AdalError: Get Token request returned http error: 401 and server response: {"error":"invalid_client","error_description":"AADSTS70002: Error validating credentials. AADSTS50032: RSA key size 1024 is less than the minimum required 2048 bits.\r\nTrace ID: 32bf21de-e77a-4419-ab2b-cdc3a9343200\r\nCorrelation ID: 291050ae-0e86-4d09-bd62-7cfc53750db9\r\nTimestamp: 2018-04-16 13:51:50Z","error_codes":[70002,50032],"timestamp":"2018-04-16 13:51:50Z","trace_id":"32bf21de-e77a-4419-ab2b-cdc3a9343200","correlation_id":"291050ae-0e86-4d09-bd62-7cfc53750db9"}
My code is as follows:
def get_private_key(filename):
with open(filename, 'r') as pem_file:
private_pem = pem_file.read()
return private_pem
context = adal.AuthenticationContext(authority_url, api_version=None)
key = get_private_key('../keys/fullkey.pem')
token = context.acquire_token_with_client_certificate(
resource_id,
client_id,
key,
thumbprint_new)
print token
No matter which .pem file I point to (I've generated multiple in an attempt to debug), I continue to receive the same error.
Any help would be hugely appreciated!
Thank you,
Mike
When using the code of client credential sample I get this error:
azure.common.AzureHttpError: {"error"{"code":"AuthenticationFailed","message":"The access token has been obtained from wrong audience or resource '00000002-0000-0000-c000-000000000000'. It should exactly match (including forward slash) with one of the allowed audiences 'https://management.core.windows.net/','https://management.azure.com/'."}}
To solve it I changed the parameter:
RESOURCE = '00000002-0000-0000-c000-000000000000'
to
RESOURCE = 'https://management.core.windows.net/'
#39 changed the setup script so that several of the dependencies are required before running python setup.py install
. Trying to install in a clean virtualenv does not work.
The setup.py
script parses the version number from the adal/__init__.py
. This can fail with certain locales on Linux when Python3 is being used:
glaubitz@suse-laptop:~/upstream/azure-activedirectory-library-for-python> LANG=C python3 setup.py build
Traceback (most recent call last):
File "setup.py", line 35, in <module>
open('adal/__init__.py').read()).group(1)
File "/usr/lib64/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
glaubitz@suse-laptop:~/upstream/azure-activedirectory-library-for-python>
This is because of the Windows encoding of __init__.py
contains a byte-order mark at the beginning of the file:
<U+FEFF>#------------------------------------------------------------------------------
simply converting __init__.py
to standard Unix format fixes the problem:
glaubitz@suse-laptop:~/upstream/azure-activedirectory-library-for-python> dos2unix adal/__init__.py
dos2unix: converting file adal/__init__.py to Unix format...
glaubitz@suse-laptop:~/upstream/azure-activedirectory-library-for-python> LANG=C python3 setup.py build
running build
running build_py
creating build
creating build/lib
creating build/lib/adal
copying adal/constants.py -> build/lib/adal
copying adal/adal_error.py -> build/lib/adal
copying adal/cache_driver.py -> build/lib/adal
copying adal/mex.py -> build/lib/adal
copying adal/xmlutil.py -> build/lib/adal
copying adal/authority.py -> build/lib/adal
copying adal/authentication_context.py -> build/lib/adal
copying adal/wstrust_response.py -> build/lib/adal
copying adal/self_signed_jwt.py -> build/lib/adal
copying adal/authentication_parameters.py -> build/lib/adal
copying adal/util.py -> build/lib/adal
copying adal/argument.py -> build/lib/adal
copying adal/user_realm.py -> build/lib/adal
copying adal/oauth2_client.py -> build/lib/adal
copying adal/token_cache.py -> build/lib/adal
copying adal/log.py -> build/lib/adal
copying adal/wstrust_request.py -> build/lib/adal
copying adal/token_request.py -> build/lib/adal
copying adal/__init__.py -> build/lib/adal
copying adal/code_request.py -> build/lib/adal
glaubitz@suse-laptop:~/upstream/azure-activedirectory-library-for-python>
This problem also affects the building of RPM packages. In fact, I stumbled over this issue when trying to build the python3 RPM package for ADAL.
Please consider plain UTF-8 for the source code encoding.
The acquire_token method is not thread-safe.
Example:
context = adal.AuthenticationContext(authority, api_version=None)
context.acquire_token_with_username_password(resource, username, password, client_id)
# Then executing the method below in parallell when the token cache expires, say with concurrent.futures.ThreadPoolExecutor will cause a KeyError.
context.acquire_token(resource, username, client_id)
# The issue seems to be a dict.pop operation during cache update which itself is not thread-safe.
To avoid warning when we follow meticulously the sample:
D:\VSProjects\azure-sdk-for-python\env3.5\lib\site-packages\adal\authentication_context.py:88: DeprecationWarning: The default behavior of including api-version=1.0 on the wire
is now deprecated.
Future version of ADAL will change the default value to None.
To ensure a smooth transition, you are recommended to explicitly
set it to None in your code now, and test out the new behavior.
context = AuthenticationContext(..., api_version=None)
""", DeprecationWarning)
How should a average Python programmer be able to easily take use of ADAL library without any tutorials?
Please give us a step by step tutorial.
We currently invoke resiliency mode when the following conditions occur: network timeout or http error codes 500, 503, 504. After discussion, we have decided to expand the error code list to include ALL http error codes 500 - 599. Please change your logic to include all of those codes for Resiliency.
Hi
How do I overcome this interactive issue?
"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID 'My Valid-Clie-ntID-xxxx-123456789101'. Send an interactive authorization request for this user and resource.
I am able to obtain a valid access token by issuing the following command
>>> token = context.acquire_token_with_client_credentials(RESOURCE, client_id, client_secret)
However, when I issue the same command after the above token has expired, I get the following error message. Please let me know if I am missing something here or if I am expected to issue a different command in order to obtain a new token. Thanks in advance.
>>> token = context.acquire_token_with_client_credentials(RESOURCE, client_id, client_secret)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/authentication_context.py", line 160, in acquire_token_with_client_credentials
return self._acquire_token(token_func)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/authentication_context.py", line 158, in token_func
return token_request.get_token_with_client_credentials(client_secret)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/token_request.py", line 304, in get_token_with_client_credentials
token = self._find_token_from_cache()
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/token_request.py", line 128, in _find_token_from_cache
return self._cache_driver.find(cache_query)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/cache_driver.py", line 182, in find
is_resource_tenant_specific)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/cache_driver.py", line 171, in _refresh_entry_if_necessary
return self._acquire_new_token_from_mrrt(entry)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/cache_driver.py", line 153, in _acquire_new_token_from_mrrt
token_response = self._refresh_function(entry, self._resource)
File "/Users/shetty/.virtualenvs/ad/lib/python2.7/site-packages/adal/token_request.py", line 137, in _get_token_with_token_response
refresh_token = entry[TOKEN_RESPONSE_FIELDS.REFRESH_TOKEN]
KeyError: 'refreshToken'
import adal
clientId = 'My Valid-Clie-ntID-xxxx-123456789101'
RESOURCE_URI = 'https://analysis.windows.net/powerbi/api'
USERNAME = '[email protected]'
PASSWORD = 'MyPassword'
AUTHORIZATION_URL = 'https://login.microsoftonline.com/common/oauth2/authorize'
context = adal.AuthenticationContext(AUTHORIZATION_URL)
token_response = context.acquire_token_with_username_password(RESOURCE_URI,USERNAME,PASSWORD,clientId)
I'm using the device_code sample to log in and automate our Azure FrontDoor API script, I've had success with the "sample" client ID a couple of weeks ago, but today when I tried using this again, I keep getting this after logging in successfully to https://aka.ms/devicelogin
...
token = context.acquire_token_with_device_code(RESOURCE, code, clientid)
File "/usr/local/lib/python3.6/site-packages/adal/authentication_context.py", line 273, in acquire_token_with_device_code
return self._acquire_token(token_func)
File "/usr/local/lib/python3.6/site-packages/adal/authentication_context.py", line 109, in _acquire_token
return token_func(self)
File "/usr/local/lib/python3.6/site-packages/adal/authentication_context.py", line 266, in token_func
token = token_request.get_token_with_device_code(user_code_info)
File "/usr/local/lib/python3.6/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 "/usr/local/lib/python3.6/site-packages/adal/oauth2_client.py", line 345, in get_token_with_polling
wire_response)
adal.adal_error.AdalError: Unexpected polling state code_expired
At first I thought this is a problem with other clients using the same clientid, so I registered my own app in Azure, copying over all the permissions that AzureFDControlPlaneInteractive had, and I run into the same error.
Hi Team,
I have Flask app deployed in Azure and my org has AD Auth/Windows Authentication (Azure on premises) wondering where should I get started and where can I get right documentation to incorporate those into my Flask web app!?
Appreciate it.
The acquire_token_with_username_password functionality does not perform as expected. The token returned with the current function returns 403 errors. This can be fixed by setting client_secret in
Oauth parameters at
This is described in
http://stackoverflow.com/questions/32341877/cant-get-client-credentials-access-token-to-authorize-power-bi
for node and also works for python
probably am missing something, but i couldn't find a way to set enable_pii =True.
unless directly setting authContext._call_context['enable_pii']=True
won't it be better to introduce an options kwargs, and merge it with GLOBAL_ADAL_OPTIONS?
and fetch it from there?
i can create a PR with the changes.
When I try to get the token using the following credentials I get the error.
RESOURCE_URI = 'https://XXXXXXX.api.crm.dynamics.com'
USERNAME = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
PASSWORD = 'XXXXX'
AUTHORIZATION_URL = '//login.windows.net/ABCDEFGH-1234-ABCD-1234-ABCDEFGHIJKL'
token_response = adal.acquire_token_with_username_password(
AUTHORIZATION_URL,
USERNAME,
PASSWORD,
resource=RESOURCE_URI
)
and the error I get is
Exception: Error:Error:Error:Get Token request returned http error: 500 and server response: {"error":"server_error","error_description":"AADSTS90036: Directory Proxy Client encountered an internal error.\r\nTrace ID: 1f39ca43-a156-4a2c-a6f6-c3281d28db52\r\nCorrelation ID: fcf8ceff-f18e-4f91-9197-ec93101d527c\r\nTimestamp: 2016-06-03 09:09:05Z","error_codes":[90036],"timestamp":"2016-06-03 09:09:05Z","trace_id":"1f39ca43-a156-4a2c-a6f6-c3281d28db52","correlation_id":"fcf8ceff-f18e-4f91-9197-ec93101d527c"} token_response:{u'timestamp': u'2016-06-03 09:09:05Z', u'trace_id': u'1f39ca43-a156-4a2c-a6f6-c3281d28db52', u'correlation_id': u'fcf8ceff-f18e-4f91-9197-ec93101d527c', u'error_description': u'AADSTS90036: Directory Proxy Client encountered an internal error.\r\nTrace ID: 1f39ca43-a156-4a2c-a6f6-c3281d28db52\r\nCorrelation ID: fcf8ceff-f18e-4f91-9197-ec93101d527c\r\nTimestamp: 2016-06-03 09:09:05Z', u'error': u'server_error', u'error_codes': [90036]} token_response:None token_response:None
As far as I can tell this isn't mentioned in the docs and it is not supported.
The endpoints seem to be hardcoded to /oauth2/token
. I tried replacing them but then ADAL tries to send the resource
parameter when calling acquire_token_with_authorization_code
and it fails with:
AADSTS90100: The 'resource' request parameter is not supported.
I was hoping to use the v2 endpoint to gain access to the incremental consent and other features but it looks like I can't for now. Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.