Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def acquire_token(self, username, password):
if self._wstrust_endpoint_version == WSTrustVersion.UNDEFINED:
raise AdalError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.')
rst = self._build_rst(username, password)
if self._wstrust_endpoint_version == WSTrustVersion.WSTRUST2005:
soap_action = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue'
else:
soap_action = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue'
headers = {'headers': {'Content-type':'application/soap+xml; charset=utf-8',
'SOAPAction': soap_action},
'body': rst}
options = util.create_request_options(self, headers)
self._log.debug("Sending RST to: %(wstrust_endpoint)s",
{"wstrust_endpoint": self._wstrust_endpoint_url})
operation = "WS-Trust RST"
resp = requests.post(self._wstrust_endpoint_url, headers=options['headers'], data=rst,
allow_redirects=True,
verify=self._call_context.get('verify_ssl', None),
proxies=self._call_context.get('proxies', None),
timeout=self._call_context.get('timeout', None))
util.log_return_correlation_id(self._log, operation, resp)
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
if not util.is_http_success(resp.status_code):
return_error_string = u"{} request returned http error: {}".format(operation, resp.status_code)
challenge_url = url
else:
validate_url_object(url)
challenge_url = url.geturl()
log_context = log.create_log_context(correlation_id)
logger = log.Logger('AuthenticationParameters', log_context)
logger.debug(
"Attempting to retrieve authentication parameters from: {0}".format(challenge_url)
)
class _options(object):
_call_context = {'log_context': log_context}
options = util.create_request_options(_options())
try:
response = requests.get(challenge_url, headers=options['headers'])
except Exception as exp:
logger.error("Authentication parameters http get failed.", exp)
raise
try:
parameters = create_authentication_parameters_from_response(response)
except Exception as exp:
logger.error("Unable to parse response in to authentication parameters.", exp)
raise
return parameters
def discover(self):
options = util.create_request_options(self, {'headers': {'Content-Type': 'application/soap+xml'}})
try:
operation = "Mex Get"
resp = requests.get(self._url, headers=options['headers'],
verify=self._call_context.get('verify_ssl', None),
proxies=self._call_context.get('proxies', None))
util.log_return_correlation_id(self._log, operation, resp)
except Exception:
self._log.exception(
"%(operation)s request failed", {"operation": operation})
raise
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
if not util.is_http_success(resp.status_code):
return_error_string = u"{} request returned http error: {}".format(operation, resp.status_code)
def _perform_dynamic_instance_discovery(self):
discovery_endpoint = self._create_instance_discovery_endpoint_from_template(
AADConstants.WORLD_WIDE_AUTHORITY)
get_options = util.create_request_options(self)
operation = "Instance Discovery"
self._log.debug("Attempting instance discover at: %(discovery_endpoint)s",
{"discovery_endpoint": discovery_endpoint.geturl()})
try:
resp = requests.get(discovery_endpoint.geturl(), headers=get_options['headers'],
verify=self._call_context.get('verify_ssl', None),
proxies=self._call_context.get('proxies', None))
util.log_return_correlation_id(self._log, operation, resp)
except Exception:
self._log.exception("%(operation)s request failed",
{"operation": operation})
raise
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
self._log.debug("Attempting instance discover at: %(discovery_endpoint)s",
{"discovery_endpoint": discovery_endpoint.geturl()})
try:
resp = requests.get(discovery_endpoint.geturl(), headers=get_options['headers'],
verify=self._call_context.get('verify_ssl', None),
proxies=self._call_context.get('proxies', None))
util.log_return_correlation_id(self._log, operation, resp)
except Exception:
self._log.exception("%(operation)s request failed",
{"operation": operation})
raise
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
if not util.is_http_success(resp.status_code):
return_error_string = u"{} request returned http error: {}".format(operation,
resp.status_code)
error_response = ""
if resp.text:
return_error_string = u"{} and server response: {}".format(return_error_string,
resp.text)
try:
error_response = resp.json()
except ValueError:
pass
raise AdalError(return_error_string, error_response)
else:
discovery_resp = resp.json()
if discovery_resp.get('tenant_discovery_endpoint'):
options = util.create_request_options(self, headers)
self._log.debug("Sending RST to: %(wstrust_endpoint)s",
{"wstrust_endpoint": self._wstrust_endpoint_url})
operation = "WS-Trust RST"
resp = requests.post(self._wstrust_endpoint_url, headers=options['headers'], data=rst,
allow_redirects=True,
verify=self._call_context.get('verify_ssl', None),
proxies=self._call_context.get('proxies', None),
timeout=self._call_context.get('timeout', None))
util.log_return_correlation_id(self._log, operation, resp)
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
if not util.is_http_success(resp.status_code):
return_error_string = u"{} request returned http error: {}".format(operation, resp.status_code)
error_response = ""
if resp.text:
return_error_string = u"{} and server response: {}".format(return_error_string, resp.text)
try:
error_response = resp.json()
except ValueError:
pass
raise AdalError(return_error_string, error_response)
else:
return self._handle_rstr(resp.text)
def discover(self):
options = util.create_request_options(self, {'headers': {'Accept':'application/json'}})
user_realm_url = self._get_user_realm_url()
self._log.debug("Performing user realm discovery at: %(user_realm_url)s",
{"user_realm_url": user_realm_url.geturl()})
operation = 'User Realm Discovery'
resp = requests.get(user_realm_url.geturl(), headers=options['headers'],
proxies=self._call_context.get('proxies', None),
verify=self._call_context.get('verify_ssl', None))
util.log_return_correlation_id(self._log, operation, resp)
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
if not util.is_http_success(resp.status_code):
return_error_string = u"{} request returned http error: {}".format(operation,
resp.status_code)
error_response = ""
if resp.text:
return_error_string = u"{} and server response: {}".format(return_error_string, resp.text)
try:
error_response = resp.json()
except ValueError:
pass
raise AdalError(return_error_string, error_response)
def _parse_id_token(self, encoded_token):
cracked_token = self._open_jwt(encoded_token)
if not cracked_token:
return
try:
b64_id_token = cracked_token['JWSPayload']
b64_decoded = util.base64_urlsafe_decode(b64_id_token)
if not b64_decoded:
self._log.warn('The returned id_token could not be base64 url safe decoded.')
return
id_token = json.loads(b64_decoded.decode('utf-8'))
except ValueError:
self._log.exception(
"The returned id_token could not be decoded: %(id_token)s",
{"id_token": encoded_token})
raise
return _extract_token_values(id_token)
for _ in range(int(max_times_for_retry)):
if self._cancel_polling_request:
raise AdalError('Polling_Request_Cancelled')
resp = requests.post(
token_url.geturl(),
data=url_encoded_code_request, headers=post_options['headers'],
proxies=self._call_context.get('proxies', None),
verify=self._call_context.get('verify_ssl', None))
if resp.status_code == 429:
resp.raise_for_status() # Will raise requests.exceptions.HTTPError
util.log_return_correlation_id(self._log, operation, resp)
wire_response = {}
if not util.is_http_success(resp.status_code):
# on error, the body should be json already
wire_response = json.loads(resp.text)
error = wire_response.get(OAuth2.DeviceCodeResponseParameters.ERROR)
if error == 'authorization_pending':
time.sleep(refresh_internal)
continue
elif error:
raise AdalError('Unexpected polling state {}'.format(error),
wire_response)
else:
try:
return self._validate_token_response(resp.text)
except Exception:
self._log.exception(
u"Error validating get token response %(access_token)s",