onelogin.saml2 package

Submodules

onelogin.saml2.auth module

OneLogin_Saml2_Auth class

Main class of SAML Python Toolkit.

Initializes the SP SAML instance

class onelogin.saml2.auth.OneLogin_Saml2_Auth(request_data, old_settings=None, custom_base_path=None)[source]

Bases: object

This class implements the SP SAML instance.

Defines the methods that you can invoke in your application in order to add SAML support (initiates SSO, initiates SLO, processes a SAML Response, a Logout Request or a Logout Response).

add_request_signature(request_data, sign_algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256')[source]

Builds the Signature of the SAML Request.

Parameters:
  • request_data (dict) – The Request parameters

  • sign_algorithm (string) – Signature algorithm method

add_response_signature(response_data, sign_algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256')[source]

Builds the Signature of the SAML Response. :param response_data: The Response parameters :type response_data: dict

Parameters:

sign_algorithm (string) – Signature algorithm method

authn_request_class

alias of OneLogin_Saml2_Authn_Request

get_attribute(name)[source]

Returns the requested SAML attribute.

Parameters:

name (string) – Name of the attribute

Returns:

Attribute value(s) if exists or None

Return type:

list

get_attributes()[source]

Returns the set of SAML attributes.

Returns:

SAML attributes

Return type:

dict

get_errors()[source]

Returns a list with code errors if something went wrong

Returns:

List of errors

Return type:

list

get_friendlyname_attribute(friendlyname)[source]

Returns the requested SAML attribute searched by FriendlyName.

Parameters:

friendlyname (string) – FriendlyName of the attribute

Returns:

Attribute value(s) if exists or None

Return type:

list

get_friendlyname_attributes()[source]

Returns the set of SAML attributes indexed by FiendlyName.

Returns:

SAML attributes

Return type:

dict

get_last_assertion_id()[source]
Returns:

The ID of the last assertion processed.

Return type:

string

get_last_assertion_issue_instant()[source]
Returns:

The IssueInstant of the last assertion processed.

Return type:

unix/posix timestamp|None

get_last_assertion_not_on_or_after()[source]

The NotOnOrAfter value of the valid SubjectConfirmationData node (if any) of the last assertion processed

get_last_authn_contexts()[source]
Returns:

The list of authentication contexts sent in the last SAML Response.

Return type:

list

get_last_error_reason()[source]

Returns the reason for the last error

Returns:

Reason of the last error

Return type:

None | string

get_last_message_id()[source]
Returns:

The ID of the last Response SAML message processed.

Return type:

string

get_last_request_id()[source]
Returns:

The ID of the last Request SAML message generated.

Return type:

string

get_last_request_xml()[source]

Retrieves the raw XML sent in the last SAML request :returns: SAML request XML :rtype: string|None

get_last_response_in_response_to()[source]
Returns:

InResponseTo attribute of the last Response SAML processed or None if it is not present.

Return type:

string

get_last_response_xml(pretty_print_if_possible=False)[source]

Retrieves the raw XML (decrypted) of the last SAML response, or the last Logout Response generated or processed :returns: SAML response XML :rtype: string|None

get_nameid()[source]

Returns the nameID.

Returns:

NameID

Return type:

string|None

get_nameid_format()[source]

Returns the nameID Format.

Returns:

NameID Format

Return type:

string|None

get_nameid_nq()[source]

Returns the nameID NameQualifier of the Assertion.

Returns:

NameID NameQualifier

Return type:

string|None

get_nameid_spnq()[source]

Returns the nameID SP NameQualifier of the Assertion.

Returns:

NameID SP NameQualifier

Return type:

string|None

get_session_expiration()[source]

Returns the SessionNotOnOrAfter from the AuthnStatement. :returns: The SessionNotOnOrAfter of the assertion :rtype: unix/posix timestamp|None

get_session_index()[source]

Returns the SessionIndex from the AuthnStatement. :returns: The SessionIndex of the assertion :rtype: string

get_settings()[source]

Returns the settings info :return: Setting info :rtype: OneLogin_Saml2_Setting object

get_slo_response_url()[source]

Gets the SLO return URL for IdP-initiated logout.

Returns:

an URL, the SLO return endpoint of the IdP

Return type:

string

get_slo_url()[source]

Gets the SLO URL.

Returns:

An URL, the SLO endpoint of the IdP

Return type:

string

get_sso_url()[source]

Gets the SSO URL.

Returns:

An URL, the SSO endpoint of the IdP

Return type:

string

is_authenticated()[source]

Checks if the user is authenticated or not.

Returns:

True if is authenticated, False if not

Return type:

bool

login(return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None)[source]

Initiates the SSO process.

Parameters:
  • return_to (string) – Optional argument. The target URL the user should be redirected to after login.

  • force_authn (bool) – Optional argument. When true the AuthNRequest will set the ForceAuthn=’true’.

  • is_passive (bool) – Optional argument. When true the AuthNRequest will set the Ispassive=’true’.

  • set_nameid_policy (bool) – Optional argument. When true the AuthNRequest will set a nameIdPolicy element.

  • name_id_value_req (string) – Optional argument. Indicates to the IdP the subject that should be authenticated

Returns:

Redirection URL

Return type:

string

logout(return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None, spnq=None)[source]

Initiates the SLO process.

Parameters:
  • return_to (string) – Optional argument. The target URL the user should be redirected to after logout.

  • name_id (string) – The NameID that will be set in the LogoutRequest.

  • session_index (string) – SessionIndex that identifies the session of the user.

  • nq – IDP Name Qualifier

  • name_id_format – The NameID Format that will be set in the LogoutRequest.

  • spnq – SP Name Qualifier

Type:

string

Type:

string

Type:

string

Returns:

Redirection URL

logout_request_class

alias of OneLogin_Saml2_Logout_Request

logout_response_class

alias of OneLogin_Saml2_Logout_Response

process_response(request_id=None)[source]

Process the SAML Response sent by the IdP.

Parameters:

request_id (string) – Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP.

Raises:

OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found

process_slo(keep_local_session=False, request_id=None, delete_session_cb=None)[source]

Process the SAML Logout Response / Logout Request sent by the IdP.

Parameters:
  • keep_local_session (bool) – When false will destroy the local session, otherwise will destroy it

  • request_id (string) – The ID of the LogoutRequest sent by this SP to the IdP

Returns:

Redirection url

redirect_to(url=None, parameters={})[source]

Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request.

Parameters:
  • url (string) – The target URL to redirect the user

  • parameters (dict) – Extra parameters to be passed as part of the URL

Returns:

Redirection URL

response_class

alias of OneLogin_Saml2_Response

set_strict(value)[source]

Set the strict mode active/disable

Parameters:

value (bool) –

store_valid_response(response)[source]
validate_request_signature(request_data)[source]

Validate Request Signature

Parameters:

request_data (dict) – The Request data

validate_response_signature(request_data)[source]

Validate Response Signature

Parameters:

request_data (dict) – The Request data

onelogin.saml2.authn_request module

OneLogin_Saml2_Authn_Request class

AuthNRequest class of SAML Python Toolkit.

class onelogin.saml2.authn_request.OneLogin_Saml2_Authn_Request(settings, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None)[source]

Bases: object

This class handles an AuthNRequest. It builds an AuthNRequest object.

get_id()[source]

Returns the AuthNRequest ID. :return: AuthNRequest ID :rtype: string

get_request(deflate=True)[source]

Returns unsigned AuthnRequest. :param deflate: It makes the deflate process optional :type: bool :return: AuthnRequest maybe deflated and base64 encoded :rtype: str object

get_xml()[source]

Returns the XML that will be sent as part of the request :return: XML request body :rtype: string

onelogin.saml2.compat module

py3 compatibility class

onelogin.saml2.compat.to_bytes(data)[source]

return bytes

onelogin.saml2.compat.to_string(data)[source]

convert to string

onelogin.saml2.compat.utf8(data)[source]

return utf8-encoded string

onelogin.saml2.constants module

OneLogin_Saml2_Constants class

Constants class of SAML Python Toolkit.

class onelogin.saml2.constants.OneLogin_Saml2_Constants[source]

Bases: object

This class defines all the constants that will be used in the SAML Python Toolkit.

AC_KERBEROS = 'urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos'
AC_PASSWORD = 'urn:oasis:names:tc:SAML:2.0:ac:classes:Password'
AC_PASSWORD_PROTECTED = 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'
AC_SMARTCARD = 'urn:oasis:names:tc:SAML:2.0:ac:classes:Smartcard'
AC_UNSPECIFIED = 'urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified'
AC_X509 = 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'
AES128_CBC = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc'
AES192_CBC = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc'
AES256_CBC = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc'
ALLOWED_CLOCK_DRIFT = 300
ATTRNAME_FORMAT_BASIC = 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic'
ATTRNAME_FORMAT_UNSPECIFIED = 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified'
ATTRNAME_FORMAT_URI = 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'
BINDING_DEFLATE = 'urn:oasis:names:tc:SAML:2.0:bindings:URL-Encoding:DEFLATE'
BINDING_HTTP_ARTIFACT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact'
BINDING_HTTP_POST = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'
BINDING_HTTP_REDIRECT = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
BINDING_SOAP = 'urn:oasis:names:tc:SAML:2.0:bindings:SOAP'
CM_BEARER = 'urn:oasis:names:tc:SAML:2.0:cm:bearer'
CM_HOLDER_KEY = 'urn:oasis:names:tc:SAML:2.0:cm:holder-of-key'
CM_SENDER_VOUCHES = 'urn:oasis:names:tc:SAML:2.0:cm:sender-vouches'
DEPRECATED_ALGORITHMS = ['http://www.w3.org/2000/09/xmldsig#dsa-sha1', 'http://www.w3.org/2000/09/xmldsig#rsa-sha1', 'http://www.w3.org/2000/09/xmldsig#sha1']
DSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1'
NAMEID_EMAIL_ADDRESS = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
NAMEID_ENCRYPTED = 'urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted'
NAMEID_ENTITY = 'urn:oasis:names:tc:SAML:2.0:nameid-format:entity'
NAMEID_KERBEROS = 'urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos'
NAMEID_PERSISTENT = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'
NAMEID_TRANSIENT = 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient'
NAMEID_UNSPECIFIED = 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified'
NAMEID_WINDOWS_DOMAIN_QUALIFIED_NAME = 'urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName'
NAMEID_X509_SUBJECT_NAME = 'urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName'
NSMAP = {'ds': 'http://www.w3.org/2000/09/xmldsig#', 'md': 'urn:oasis:names:tc:SAML:2.0:metadata', 'saml': 'urn:oasis:names:tc:SAML:2.0:assertion', 'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol', 'xenc': 'http://www.w3.org/2001/04/xmlenc#'}
NS_DS = 'http://www.w3.org/2000/09/xmldsig#'
NS_MD = 'urn:oasis:names:tc:SAML:2.0:metadata'
NS_PREFIX_DS = 'ds'
NS_PREFIX_MD = 'md'
NS_PREFIX_SAML = 'saml'
NS_PREFIX_SAMLP = 'samlp'
NS_PREFIX_XENC = 'xenc'
NS_PREFIX_XS = 'xs'
NS_PREFIX_XSD = 'xsd'
NS_PREFIX_XSI = 'xsi'
NS_SAML = 'urn:oasis:names:tc:SAML:2.0:assertion'
NS_SAMLP = 'urn:oasis:names:tc:SAML:2.0:protocol'
NS_SOAP = 'http://schemas.xmlsoap.org/soap/envelope/'
NS_XENC = 'http://www.w3.org/2001/04/xmlenc#'
NS_XS = 'http://www.w3.org/2001/XMLSchema'
NS_XSI = 'http://www.w3.org/2001/XMLSchema-instance'
RSA_1_5 = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5'
RSA_OAEP_MGF1P = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p'
RSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
RSA_SHA256 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'
RSA_SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'
RSA_SHA512 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'
SHA1 = 'http://www.w3.org/2000/09/xmldsig#sha1'
SHA256 = 'http://www.w3.org/2001/04/xmlenc#sha256'
SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#sha384'
SHA512 = 'http://www.w3.org/2001/04/xmlenc#sha512'
STATUS_NO_PASSIVE = 'urn:oasis:names:tc:SAML:2.0:status:NoPassive'
STATUS_PARTIAL_LOGOUT = 'urn:oasis:names:tc:SAML:2.0:status:PartialLogout'
STATUS_PROXY_COUNT_EXCEEDED = 'urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded'
STATUS_REQUESTER = 'urn:oasis:names:tc:SAML:2.0:status:Requester'
STATUS_RESPONDER = 'urn:oasis:names:tc:SAML:2.0:status:Responder'
STATUS_SUCCESS = 'urn:oasis:names:tc:SAML:2.0:status:Success'
STATUS_VERSION_MISMATCH = 'urn:oasis:names:tc:SAML:2.0:status:VersionMismatch'
TRIPLEDES_CBC = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc'

onelogin.saml2.errors module

OneLogin_Saml2_Error class

Error class of SAML Python Toolkit.

Defines common Error codes and has a custom initializator.

exception onelogin.saml2.errors.OneLogin_Saml2_Error(message, code=0, errors=None)[source]

Bases: Exception

This class implements a custom Exception handler. Defines custom error codes.

CERT_NOT_FOUND = 4
METADATA_SP_INVALID = 3
PRIVATE_KEY_FILE_NOT_FOUND = 7
PRIVATE_KEY_NOT_FOUND = 13
PUBLIC_CERT_FILE_NOT_FOUND = 6
REDIRECT_INVALID_URL = 5
SAML_LOGOUTMESSAGE_NOT_FOUND = 9
SAML_LOGOUTREQUEST_INVALID = 10
SAML_LOGOUTRESPONSE_INVALID = 11
SAML_RESPONSE_NOT_FOUND = 8
SAML_SINGLE_LOGOUT_NOT_SUPPORTED = 12
SETTINGS_FILE_NOT_FOUND = 0
SETTINGS_INVALID = 2
SETTINGS_INVALID_SYNTAX = 1
SP_CERTS_NOT_FOUND = 4
UNSUPPORTED_SETTINGS_OBJECT = 14
exception onelogin.saml2.errors.OneLogin_Saml2_ValidationError(message, code=0, errors=None)[source]

Bases: Exception

This class implements another custom Exception handler, related to exceptions that happens during validation process. Defines custom error codes .

ASSERTION_EXPIRED = 20
ASSERTION_TOO_EARLY = 19
AUTHN_CONTEXT_MISMATCH = 45
CHILDREN_NODE_NOT_FOUND_IN_KEYINFO = 36
DEPRECATED_DIGEST_METHOD = 47
DEPRECATED_SIGNATURE_METHOD = 46
DUPLICATED_ATTRIBUTE_NAME_FOUND = 41
DUPLICATED_ID_IN_SIGNED_ELEMENTS = 8
DUPLICATED_REFERENCE_IN_SIGNED_ELEMENTS = 10
EMPTY_DESTINATION = 25
EMPTY_NAMEID = 39
ENCRYPTED_ATTRIBUTES = 23
ID_NOT_FOUND_IN_SIGNED_ELEMENT = 7
INVALID_SIGNATURE = 42
INVALID_SIGNED_ELEMENT = 9
INVALID_XML_FORMAT = 14
ISSUER_MULTIPLE_IN_RESPONSE = 27
ISSUER_NOT_FOUND_IN_ASSERTION = 28
KEYINFO_NOT_FOUND_IN_ENCRYPTED_DATA = 35
MISSING_CONDITIONS = 18
MISSING_ID = 1
MISSING_STATUS = 3
MISSING_STATUS_CODE = 4
NO_ATTRIBUTESTATEMENT = 22
NO_ENCRYPTED_ASSERTION = 16
NO_ENCRYPTED_NAMEID = 17
NO_NAMEID = 38
NO_SIGNATURE_FOUND = 34
NO_SIGNED_ASSERTION = 33
NO_SIGNED_MESSAGE = 32
RESPONSE_EXPIRED = 44
SESSION_EXPIRED = 30
SP_NAME_QUALIFIER_NAME_MISMATCH = 40
STATUS_CODE_IS_NOT_SUCCESS = 5
UNEXPECTED_SIGNED_ELEMENTS = 11
UNSUPPORTED_RETRIEVAL_METHOD = 37
UNSUPPORTED_SAML_VERSION = 0
WRONG_AUDIENCE = 26
WRONG_DESTINATION = 24
WRONG_INRESPONSETO = 15
WRONG_ISSUER = 29
WRONG_NUMBER_OF_ASSERTIONS = 2
WRONG_NUMBER_OF_AUTHSTATEMENTS = 21
WRONG_NUMBER_OF_SIGNATURES = 43
WRONG_NUMBER_OF_SIGNATURES_IN_ASSERTION = 13
WRONG_NUMBER_OF_SIGNATURES_IN_RESPONSE = 12
WRONG_SIGNED_ELEMENT = 6
WRONG_SUBJECTCONFIRMATION = 31

onelogin.saml2.idp_metadata_parser module

OneLogin_Saml2_IdPMetadataParser class Metadata class of SAML Python Toolkit.

class onelogin.saml2.idp_metadata_parser.OneLogin_Saml2_IdPMetadataParser[source]

Bases: object

A class that contain methods related to obtaining and parsing metadata from IdP

This class does not validate in any way the URL that is introduced, make sure to validate it properly before use it in a get_metadata method.

classmethod get_metadata(url, validate_cert=True, timeout=None, headers=None)[source]

Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string

Parameters:
  • validate_cert (bool) – If the url uses https schema, that flag enables or not the verification of the associated certificate.

  • timeout (int) – Timeout in seconds to wait for metadata response

  • headers (dict) – Extra headers to send in the request

Returns:

metadata XML

Return type:

string

static merge_settings(settings, new_metadata_settings)[source]

Will update the settings with the provided new settings data extracted from the IdP metadata :param settings: Current settings dict data :type settings: dict :param new_metadata_settings: Settings to be merged (extracted from IdP metadata after parsing) :type new_metadata_settings: dict :returns: merged settings :rtype: dict

classmethod parse(idp_metadata, required_sso_binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', required_slo_binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect', entity_id=None)[source]

Parses the Identity Provider metadata and return a dict with extracted data.

If there are multiple <IDPSSODescriptor> tags, parse only the first.

Parses only those SSO endpoints with the same binding as given by the required_sso_binding parameter.

Parses only those SLO endpoints with the same binding as given by the required_slo_binding parameter.

If the metadata specifies multiple SSO endpoints with the required binding, extract only the first (the same holds true for SLO endpoints).

Parameters:
  • idp_metadata (string) – XML of the Identity Provider Metadata.

  • required_sso_binding (one of OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT or OneLogin_Saml2_Constants.BINDING_HTTP_POST) – Parse only POST or REDIRECT SSO endpoints.

  • required_slo_binding (one of OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT or OneLogin_Saml2_Constants.BINDING_HTTP_POST) – Parse only POST or REDIRECT SLO endpoints.

  • entity_id (string) – Specify the entity_id of the EntityDescriptor that you want to parse a XML that contains multiple EntityDescriptor.

Returns:

settings dict with extracted data

Return type:

dict

classmethod parse_remote(url, validate_cert=True, entity_id=None, timeout=None, **kwargs)[source]

Gets the metadata XML from the provided URL and parse it, returning a dict with extracted data :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string

Parameters:
  • validate_cert (bool) – If the url uses https schema, that flag enables or not the verification of the associated certificate.

  • entity_id (string) – Specify the entity_id of the EntityDescriptor that you want to parse a XML that contains multiple EntityDescriptor.

  • timeout (int) – Timeout in seconds to wait for metadata response

Returns:

settings dict with extracted data

Return type:

dict

onelogin.saml2.idp_metadata_parser.dict_deep_merge(a, b, path=None)[source]

Deep-merge dictionary b into dictionary a.

Kudos to http://stackoverflow.com/a/7205107/145400

onelogin.saml2.logout_request module

OneLogin_Saml2_Logout_Request class

Logout Request class of SAML Python Toolkit.

class onelogin.saml2.logout_request.OneLogin_Saml2_Logout_Request(settings, request=None, name_id=None, session_index=None, nq=None, name_id_format=None, spnq=None)[source]

Bases: object

This class handles a Logout Request.

Builds a Logout Response object and validates it.

get_error()[source]

After executing a validation process, if it fails this method returns the cause

classmethod get_id(request)[source]

Returns the ID of the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: string ID :rtype: str object

classmethod get_issuer(request)[source]

Gets the Issuer of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :return: The Issuer :rtype: string

classmethod get_nameid(request, key=None)[source]

Gets the NameID of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :param key: The SP key :type key: string :return: Name ID Value :rtype: string

classmethod get_nameid_data(request, key=None)[source]

Gets the NameID Data of the the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :param key: The SP key :type key: string :return: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict

classmethod get_nameid_format(request, key=None)[source]

Gets the NameID Format of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :param key: The SP key :type key: string :return: Name ID Format :rtype: string

get_request(deflate=True)[source]

Returns the Logout Request deflated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Request maybe deflated and base64 encoded :rtype: str object

classmethod get_session_indexes(request)[source]

Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list

get_xml()[source]

Returns the XML that will be sent as part of the request or that was received at the SP :return: XML request body :rtype: string

is_valid(request_data, raise_exceptions=False)[source]

Checks if the Logout Request received is valid :param request_data: Request Data :type request_data: dict

Parameters:

raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Returns:

If the Logout Request is or not valid

Return type:

boolean

onelogin.saml2.logout_response module

OneLogin_Saml2_Logout_Response class

Logout Response class of SAML Python Toolkit.

class onelogin.saml2.logout_response.OneLogin_Saml2_Logout_Response(settings, response=None)[source]

Bases: object

This class handles a Logout Response. It Builds or parses a Logout Response object and validates it.

build(in_response_to, status='urn:oasis:names:tc:SAML:2.0:status:Success')[source]

Creates a Logout Response object. :param in_response_to: InResponseTo value for the Logout Response. :type in_response_to: string :param: status: The status of the response :type: status: string

get_error()[source]

After executing a validation process, if it fails this method returns the cause

get_in_response_to()[source]

Gets the ID of the LogoutRequest which this response is in response to :returns: ID of LogoutRequest this LogoutResponse is in response to or None if it is not present :rtype: str

get_issuer()[source]

Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string

get_response(deflate=True)[source]

Returns a Logout Response object. :param deflate: It makes the deflate process optional :type: bool :return: Logout Response maybe deflated and base64 encoded :rtype: string

get_status()[source]

Gets the Status :return: The Status :rtype: string

get_xml()[source]

Returns the XML that will be sent as part of the response or that was received at the SP :return: XML response body :rtype: string

is_valid(request_data, request_id=None, raise_exceptions=False)[source]

Determines if the SAML LogoutResponse is valid :param request_id: The ID of the LogoutRequest sent by this SP to the IdP :type request_id: string

Parameters:

raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Returns:

Returns if the SAML LogoutResponse is or not valid

Return type:

boolean

onelogin.saml2.metadata module

OneLoginSaml2Metadata class

Metadata class of SAML Python Toolkit.

class onelogin.saml2.metadata.OneLogin_Saml2_Metadata[source]

Bases: object

A class that contains methods related to the metadata of the SP

TIME_CACHED = 604800
TIME_VALID = 172800
classmethod add_x509_key_descriptors(metadata, cert=None, add_encryption=True)[source]

Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt

Parameters:
  • metadata (string) – SAML Metadata XML

  • cert (string) – x509 cert

  • add_encryption (boolean) – Determines if the KeyDescriptor[use=”encryption”] should be added.

Returns:

Metadata with KeyDescriptors

Return type:

string

classmethod builder(sp, authnsign=False, wsign=False, valid_until=None, cache_duration=None, contacts=None, organization=None)[source]

Builds the metadata of the SP

Parameters:
  • sp (string) – The SP data

  • authnsign (string) – authnRequestsSigned attribute

  • wsign (string) – wantAssertionsSigned attribute

  • valid_until (string|DateTime|Timestamp) – Metadata’s expiry date

  • cache_duration (int|string) – Duration of the cache in seconds

  • contacts (dict) – Contacts info

  • organization (dict) – Organization info

static sign_metadata(metadata, key, cert, sign_algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256', digest_algorithm='http://www.w3.org/2001/04/xmlenc#sha256')[source]

Signs the metadata with the key/cert provided

Parameters:
  • metadata (string) – SAML Metadata XML

  • key (string) – x509 key

  • cert (string) – x509 cert

  • sign_algorithm (string) – Signature algorithm method

  • digest_algorithm (string) – Digest algorithm method

Returns:

Signed Metadata

Return type:

string

onelogin.saml2.response module

OneLogin_Saml2_Response class

SAML Response class of SAML Python Toolkit.

class onelogin.saml2.response.OneLogin_Saml2_Response(settings, response)[source]

Bases: object

This class handles a SAML Response. It parses or validates a Logout Response object.

check_one_authnstatement()[source]

Checks that the samlp:Response/saml:Assertion/saml:AuthnStatement element exists and is unique.

check_one_condition()[source]

Checks that the samlp:Response/saml:Assertion/saml:Conditions element exists and is unique.

check_status()[source]

Check if the status of the response is success or not

Raises:

Exception. If the status is not success

get_assertion_id()[source]
Returns:

the ID of the assertion in the response

Return type:

string

get_assertion_issue_instant()[source]
Returns:

the IssueInstant of the assertion in the response

Return type:

unix/posix timestamp|None

get_assertion_not_on_or_after()[source]

Returns the NotOnOrAfter value of the valid SubjectConfirmationData node if any

get_attributes()[source]

Gets the Attributes from the AttributeStatement element. EncryptedAttributes are not supported

get_audiences()[source]

Gets the audiences

Returns:

The valid audiences for the SAML Response

Return type:

list

get_authn_contexts()[source]

Gets the authentication contexts

Returns:

The authentication classes for the SAML Response

Return type:

list

get_error()[source]

After executing a validation process, if it fails this method returns the cause

get_friendlyname_attributes()[source]

Gets the Attributes from the AttributeStatement element indexed by FiendlyName. EncryptedAttributes are not supported

get_id()[source]
Returns:

the ID of the response

Return type:

string

get_in_response_to()[source]

Gets the ID of the request which this response is in response to :returns: ID of AuthNRequest this Response is in response to or None if it is not present :rtype: str

get_issuers()[source]

Gets the issuers (from message and from assertion)

Returns:

The issuers

Return type:

list

get_nameid()[source]

Gets the NameID provided by the SAML Response from the IdP

Returns:

NameID (value)

Return type:

string|None

get_nameid_data()[source]

Gets the NameID Data provided by the SAML Response from the IdP

Returns:

Name ID Data (Value, Format, NameQualifier, SPNameQualifier)

Return type:

dict

get_nameid_format()[source]

Gets the NameID Format provided by the SAML Response from the IdP

Returns:

NameID Format

Return type:

string|None

get_nameid_nq()[source]

Gets the NameID NameQualifier provided by the SAML Response from the IdP

Returns:

NameID NameQualifier

Return type:

string|None

get_nameid_spnq()[source]

Gets the NameID SP NameQualifier provided by the SAML response from the IdP.

Returns:

NameID SP NameQualifier

Return type:

string|None

get_session_index()[source]

Gets the SessionIndex from the AuthnStatement Could be used to be stored in the local session in order to be used in a future Logout Request that the SP could send to the SP, to set what specific session must be deleted

Returns:

The SessionIndex value

Return type:

string|None

get_session_not_on_or_after()[source]

Gets the SessionNotOnOrAfter from the AuthnStatement Could be used to set the local session expiration

Returns:

The SessionNotOnOrAfter value

Return type:

time|None

get_xml_document()[source]

Returns the SAML Response document (If contains an encrypted assertion, decrypts it)

Returns:

Decrypted XML response document

Return type:

DOMDocument

is_valid(request_data, request_id=None, raise_exceptions=False)[source]

Validates the response object.

Parameters:
  • request_data (dict) – Request Data

  • request_id (string) – Optional argument. The ID of the AuthNRequest sent by this SP to the IdP

  • raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Returns:

True if the SAML Response is valid, False if not

Return type:

bool

process_signed_elements()[source]
Verifies the signature nodes:
  • Checks that are Response or Assertion

  • Check that IDs and reference URI are unique and consistent.

Returns:

The signed elements tag names

Return type:

list

validate_num_assertions()[source]

Verifies that the document only contains a single Assertion (encrypted or not)

Returns:

True if only 1 assertion encrypted or not

Return type:

bool

validate_signed_elements(signed_elements)[source]

Verifies that the document has the expected signed nodes.

Parameters:
  • signed_elements (list) – The signed elements to be checked

  • raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

validate_timestamps()[source]

Verifies that the document is valid according to Conditions Element

Returns:

True if the condition is valid, False otherwise

Return type:

bool

onelogin.saml2.settings module

OneLogin_Saml2_Settings class

Copyright (c) 2010-2021 OneLogin, Inc. MIT License

Setting class of OneLogin’s Python Toolkit.

class onelogin.saml2.settings.OneLogin_Saml2_Settings(settings=None, custom_base_path=None, sp_validation_only=False)[source]

Bases: object

Handles the settings of the Python toolkits.

check_idp_settings(settings)[source]

Checks the IdP settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the IdP settings data :rtype: list

check_settings(settings)[source]

Checks the settings info.

Parameters:

settings (dict) – Dict with settings data

Returns:

Errors found on the settings data

Return type:

list

check_sp_certs()[source]

Checks if the x509 certs of the SP exists and are valid. :returns: If the x509 certs of the SP exists and are valid :rtype: boolean

check_sp_settings(settings)[source]

Checks the SP settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the SP settings data :rtype: list

format_idp_cert()[source]

Formats the IdP cert.

format_idp_cert_multi()[source]

Formats the Multple IdP certs.

format_sp_cert()[source]

Formats the SP cert.

format_sp_cert_new()[source]

Formats the SP cert.

format_sp_key()[source]

Formats the private key.

get_base_path()[source]

Returns base path

Returns:

The base toolkit folder path

Return type:

string

get_cert_path()[source]

Returns cert path

Returns:

The cert folder path

Return type:

string

get_contacts()[source]

Gets contact data.

Returns:

Contacts info

Return type:

dict

get_errors()[source]

Returns an array with the errors, the array is empty when the settings is ok.

Returns:

Errors

Return type:

list

get_idp_cert()[source]

Returns the x509 public cert of the IdP. :returns: IdP public cert :rtype: string

get_idp_data()[source]

Gets the IdP data.

Returns:

IdP info

Return type:

dict

get_idp_slo_response_url()[source]

Gets the IdP SLO return URL for IdP-initiated logout.

Returns:

an URL, the SLO return endpoint of the IdP

Return type:

string

get_idp_slo_url()[source]

Gets the IdP SLO URL.

Returns:

An URL, the SLO endpoint of the IdP

Return type:

string

get_idp_sso_url()[source]

Gets the IdP SSO URL.

Returns:

An URL, the SSO endpoint of the IdP

Return type:

string

get_lib_path()[source]

Returns lib path

Returns:

The library folder path

Return type:

string

get_organization()[source]

Gets organization data.

Returns:

Organization info

Return type:

dict

get_schemas_path()[source]

Returns schema path

Returns:

The schema folder path

Return type:

string

get_security_data()[source]

Gets security data.

Returns:

Security info

Return type:

dict

get_sp_cert()[source]

Returns the x509 public cert of the SP. :returns: SP public cert :rtype: string or None

get_sp_cert_new()[source]

Returns the x509 public of the SP planned to be used soon instead the other public cert :returns: SP public cert new :rtype: string or None

get_sp_data()[source]

Gets the SP data.

Returns:

SP info

Return type:

dict

get_sp_key()[source]

Returns the x509 private key of the SP. :returns: SP private key :rtype: string or None

get_sp_metadata()[source]

Gets the SP metadata. The XML representation. :returns: SP metadata (xml) :rtype: string

is_debug_active()[source]

Returns if the debug is active.

Returns:

Debug parameter

Return type:

boolean

is_strict()[source]

Returns if the ‘strict’ mode is active.

Returns:

Strict parameter

Return type:

boolean

metadata_class

alias of OneLogin_Saml2_Metadata

set_cert_path(path)[source]

Set a new cert path

set_strict(value)[source]

Activates or deactivates the strict mode.

Parameters:

value (boolean) – Strict parameter

validate_metadata(xml)[source]

Validates an XML SP Metadata.

Parameters:

xml (string) – Metadata’s XML that will be validate

Returns:

The list of found errors

Return type:

list

onelogin.saml2.settings.validate_url(url, allow_single_label_domain=False)[source]

Auxiliary method to validate an urllib :param url: An url to be validated :type url: string :param allow_single_label_domain: In order to allow or not single label domain :type url: bool :returns: True if the url is valid :rtype: bool

onelogin.saml2.utils module

OneLogin_Saml2_Utils class

Auxiliary class of SAML Python Toolkit.

class onelogin.saml2.utils.OneLogin_Saml2_Utils[source]

Bases: object

Auxiliary class that contains several utility methods to parse time, urls, add sign, encrypt, decrypt, sign validation, handle xml …

ASSERTION_SIGNATURE_XPATH = '/samlp:Response/saml:Assertion/ds:Signature'
RESPONSE_SIGNATURE_XPATH = '/samlp:Response/ds:Signature'
TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
TIME_FORMAT_2 = '%Y-%m-%dT%H:%M:%S.%fZ'
TIME_FORMAT_WITH_FRAGMENT = re.compile('^(\\d{4,4}-\\d{2,2}-\\d{2,2}T\\d{2,2}:\\d{2,2}:\\d{2,2})(\\.\\d*)?Z?$')
static add_sign(xml, key, cert, debug=False, sign_algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256', digest_algorithm='http://www.w3.org/2001/04/xmlenc#sha256')[source]

Adds signature key and senders certificate to an element (Message or Assertion).

Parameters:
  • xml – The element we should sign

  • key – The private key

  • cert – The public

  • debug – Activate the xmlsec debug

  • sign_algorithm (string) – Signature algorithm method

  • digest_algorithm (string) – Digest algorithm method

Type:

string | Document

Type:

string

Type:

string

Type:

bool

Returns:

Signed XML

Return type:

string

static b64decode(data)[source]

base64 decode

static b64encode(data)[source]

base64 encode

static calculate_x509_fingerprint(x509_cert, alg='sha1')[source]

Calculates the fingerprint of a formatted x509cert.

Parameters:
  • x509_cert – x509 cert formatted

  • alg – The algorithm to build the fingerprint

Type:

string

Type:

string

Returns:

fingerprint

Return type:

string

static decode_base64_and_inflate(value, ignore_zip=False)[source]

base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :param ignore_zip: ignore zip errors :returns: the string after decoding and inflating :rtype: string

static decrypt_element(encrypted_data, key, debug=False, inplace=False)[source]

Decrypts an encrypted element.

Parameters:
  • encrypted_data – The encrypted data.

  • key – The key.

  • debug – Activate the xmlsec debug

  • inplace – update passed data with decrypted result

Type:

lxml.etree.Element | DOMElement | basestring

Type:

string

Type:

bool

Type:

bool

Returns:

The decrypted element.

Return type:

lxml.etree.Element

static deflate_and_base64_encode(value)[source]

Deflates and then base64 encodes a string :param value: The string to deflate and encode :type value: string :returns: The deflated and encoded string :rtype: string

static delete_local_session(callback=None)[source]

Deletes the local session.

static escape_url(url, lowercase_urlencoding=False)[source]

escape the non-safe symbols in url The encoding used by ADFS 3.0 is not compatible with python’s quote_plus (ADFS produces lower case hex numbers and quote_plus produces upper case hex numbers) :param url: the url to escape :type url: str

Parameters:

lowercase_urlencoding (boolean) – lowercase or no

Returns:

the escaped url

:rtype str

static format_cert(cert, heads=True)[source]

Returns a x509 cert (adding header & footer if required).

Parameters:
  • cert – A x509 unformatted cert

  • heads – True if we want to include head and footer

Type:

string

Type:

boolean

Returns:

Formatted cert

Return type:

string

static format_finger_print(fingerprint)[source]

Formats a fingerprint.

Parameters:

fingerprint – fingerprint

Type:

string

Returns:

Formatted fingerprint

Return type:

string

static format_private_key(key, heads=True)[source]

Returns a private key (adding header & footer if required).

:param key A private key :type: string

Parameters:

heads – True if we want to include head and footer

Type:

boolean

Returns:

Formated private key

Return type:

string

static generate_name_id(value, sp_nq, sp_format=None, cert=None, debug=False, nq=None)[source]

Generates a nameID.

Parameters:
  • value – fingerprint

  • sp_nq – SP Name Qualifier

  • sp_format – SP Format

  • cert – IdP Public Cert to encrypt the nameID

  • debug – Activate the xmlsec debug

  • nq – IDP Name Qualifier

Type:

string

Type:

string

Type:

string

Type:

string

Type:

bool

Returns:

DOMElement | XMLSec nameID

Return type:

string

Type:

string

static generate_unique_id()[source]

Generates an unique string (used for example as ID for assertions).

Returns:

A unique string

Return type:

string

static get_expire_time(cache_duration=None, valid_until=None)[source]

Compares 2 dates and returns the earliest.

Parameters:
  • cache_duration – The duration, as a string.

  • valid_until – The valid until date, as a string or as a timestamp

Type:

string

Type:

string

Returns:

The expiration time.

Return type:

int

static get_self_host(request_data)[source]

Returns the current host (which may include a port number part).

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

The current host

Return type:

string

static get_self_routed_url_no_query(request_data)[source]

Returns the routed URL of the current host + current view.

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

The url of current host + current view

Return type:

string

static get_self_url(request_data)[source]

Returns the URL of the current host + current view + query.

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

The url of current host + current view + query

Return type:

string

static get_self_url_host(request_data)[source]

Returns the protocol + the current host + the port (if different than common ports).

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

Url

Return type:

string

static get_self_url_no_query(request_data)[source]

Returns the URL of the current host + current view.

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

The url of current host + current view

Return type:

string

static get_status(dom)[source]

Gets Status from a Response.

Parameters:

dom – The Response as XML

Type:

Document

Returns:

The Status, an array with the code and a message.

Return type:

dict

static is_https(request_data)[source]

Checks if https or http.

Parameters:

request_data – The request as a dict

Type:

dict

Returns:

False if https is not active

Return type:

boolean

static normalize_url(url)[source]

Returns normalized URL for comparison. This method converts the netloc to lowercase, as it should be case-insensitive (per RFC 4343, RFC 7617) If standardization fails, the original URL is returned Python documentation indicates that URL split also normalizes query strings if empty query fields are present

Parameters:

url (String) – URL

Returns:

A normalized URL, or the given URL string if parsing fails

Return type:

String

static now()[source]
Returns:

unix timestamp of actual time.

Return type:

int

static parse_SAML_to_time(timestr)[source]

Converts a SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(.s+)?Z to a UNIX timestamp. The sub-second part is ignored.

Parameters:

timestr – The time we should convert (SAML Timestamp).

Type:

string

Returns:

Converted to a unix timestamp.

Return type:

int

static parse_duration(duration, timestamp=None)[source]

Interprets a ISO8601 duration value relative to a given timestamp.

Parameters:
  • duration – The duration, as a string.

  • timestamp – The unix timestamp we should apply the duration to. Optional, default to the current time.

Type:

string

Type:

string

Returns:

The new timestamp, after the duration is applied.

Return type:

int

static parse_time_to_SAML(time)[source]

Converts a UNIX timestamp to SAML2 timestamp on the form yyyy-mm-ddThh:mm:ss(.s+)?Z.

Parameters:

time – The time we should convert (DateTime).

Type:

string

Returns:

SAML2 timestamp.

Return type:

string

static redirect(url, parameters={}, request_data={})[source]

Executes a redirection to the provided url (or return the target url).

Parameters:
  • url – The target url

  • parameters – Extra parameters to be passed as part of the url

  • request_data – The request as a dict

Type:

string

Type:

dict

Type:

dict

Returns:

Url

Return type:

string

static sign_binary(msg, key, algorithm=__Transform('rsa-sha256', 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256', 8), debug=False)[source]

Sign binary message

Parameters:
  • msg – The element we should validate

  • key – The private key

  • debug – Activate the xmlsec debug

Type:

bytes

Type:

string

Type:

bool

:return signed message :rtype str

static validate_binary_sign(signed_query, signature, cert=None, algorithm='http://www.w3.org/2001/04/xmldsig-more#rsa-sha256', debug=False)[source]

Validates signed binary data (Used to validate GET Signature).

Parameters:
  • signed_query – The element we should validate

  • signature – The signature that will be validate

  • cert – The public cert

  • algorithm – Signature algorithm

  • debug – Activate the xmlsec debug

Type:

string

Type:

string

Type:

string

Type:

string

Type:

bool

static validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False)[source]

Validates a signature of a EntityDescriptor.

Parameters:
  • xml – The element we should validate

  • cert – The public cert

  • fingerprint – The fingerprint of the public cert

  • fingerprintalg – The algorithm used to build the fingerprint

  • validatecert – If true, will verify the signature and if the cert is valid.

  • debug – Activate the xmlsec debug

  • raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Type:

string | Document

Type:

string

Type:

string

Type:

string

Type:

bool

Type:

bool

static validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False)[source]

Validates a signature node.

Parameters:
  • signature_node – The signature node

  • xml – The element we should validate

  • cert – The public cert

  • fingerprint – The fingerprint of the public cert

  • fingerprintalg – The algorithm used to build the fingerprint

  • validatecert – If true, will verify the signature and if the cert is valid.

  • debug – Activate the xmlsec debug

  • raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Type:

Node

Type:

Document

Type:

string

Type:

string

Type:

string

Type:

bool

Type:

bool

static validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False, xpath=None, multicerts=None)[source]

Validates a signature (Message or Assertion).

Parameters:
  • xml – The element we should validate

  • cert – The public cert

  • fingerprint – The fingerprint of the public cert

  • fingerprintalg – The algorithm used to build the fingerprint

  • validatecert – If true, will verify the signature and if the cert is valid.

  • debug – Activate the xmlsec debug

  • xpath – The xpath of the signed element

  • multicerts – Multiple public certs

  • raise_exceptions (Boolean) – Whether to return false on failure or raise an exception

Type:

string | Document

Type:

string

Type:

string

Type:

string

Type:

bool

Type:

bool

Type:

string

Type:

list

onelogin.saml2.utils.return_false_on_exception(func)[source]

Decorator. When applied to a function, it will, by default, suppress any exceptions raised by that function and return False. It may be overridden by passing a “raise_exceptions” keyword argument when calling the wrapped function.

onelogin.saml2.xml_templates module

OneLogin_Saml2_Auth class

Main class of SAML Python Toolkit.

Initializes the SP SAML instance

class onelogin.saml2.xml_templates.OneLogin_Saml2_Templates[source]

Bases: object

ATTRIBUTE = '\n        <saml:Attribute Name="%s" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">\n            <saml:AttributeValue xsi:type="xs:string">%s</saml:AttributeValue>\n        </saml:Attribute>'
AUTHN_REQUEST = '<samlp:AuthnRequest\n  xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"\n  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"\n  ID="%(id)s"\n  Version="2.0"%(provider_name)s%(force_authn_str)s%(is_passive_str)s\n  IssueInstant="%(issue_instant)s"\n  Destination="%(destination)s"\n  ProtocolBinding="%(acs_binding)s"\n  AssertionConsumerServiceURL="%(assertion_url)s"%(attr_consuming_service_str)s>\n    <saml:Issuer>%(entity_id)s</saml:Issuer>%(subject_str)s%(nameid_policy_str)s\n%(requested_authn_context_str)s\n</samlp:AuthnRequest>'
LOGOUT_REQUEST = '<samlp:LogoutRequest\n  xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"\n  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"\n  ID="%(id)s"\n  Version="2.0"\n  IssueInstant="%(issue_instant)s"\n  Destination="%(single_logout_url)s">\n    <saml:Issuer>%(entity_id)s</saml:Issuer>\n    %(name_id)s\n    %(session_index)s\n</samlp:LogoutRequest>'
LOGOUT_RESPONSE = '<samlp:LogoutResponse\n  xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"\n  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"\n  ID="%(id)s"\n  Version="2.0"\n  IssueInstant="%(issue_instant)s"\n  Destination="%(destination)s"\n  InResponseTo="%(in_response_to)s">\n    <saml:Issuer>%(entity_id)s</saml:Issuer>\n    <samlp:Status>\n        <samlp:StatusCode Value="%(status)s" />\n    </samlp:Status>\n</samlp:LogoutResponse>'
MD_ATTR_CONSUMER_SERVICE = '        <md:AttributeConsumingService index="1">\n            <md:ServiceName xml:lang="en">%(service_name)s</md:ServiceName>\n%(attr_cs_desc)s%(requested_attribute_str)s\n        </md:AttributeConsumingService>\n'
MD_CONTACT_PERSON = '    <md:ContactPerson contactType="%(type)s">\n        <md:GivenName>%(name)s</md:GivenName>\n        <md:EmailAddress>%(email)s</md:EmailAddress>\n    </md:ContactPerson>'
MD_ENTITY_DESCRIPTOR = '<?xml version="1.0"?>\n<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"\n                     %(valid)s\n                     %(cache)s\n                     entityID="%(entity_id)s">\n    <md:SPSSODescriptor AuthnRequestsSigned="%(authnsign)s" WantAssertionsSigned="%(wsign)s" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">\n%(sls)s        <md:NameIDFormat>%(name_id_format)s</md:NameIDFormat>\n        <md:AssertionConsumerService Binding="%(binding)s"\n                                     Location="%(location)s"\n                                     index="1" />\n%(attribute_consuming_service)s    </md:SPSSODescriptor>\n%(organization)s\n%(contacts)s\n</md:EntityDescriptor>'
MD_ORGANISATION = '    <md:Organization>\n        <md:OrganizationName xml:lang="%(lang)s">%(name)s</md:OrganizationName>\n        <md:OrganizationDisplayName xml:lang="%(lang)s">%(display_name)s</md:OrganizationDisplayName>\n        <md:OrganizationURL xml:lang="%(lang)s">%(url)s</md:OrganizationURL>\n    </md:Organization>'
MD_REQUESTED_ATTRIBUTE = '            <md:RequestedAttribute Name="%(req_attr_name)s"%(req_attr_nameformat_str)s%(req_attr_isrequired_str)s%(req_attr_aux_str)s'
MD_SLS = '        <md:SingleLogoutService Binding="%(binding)s"\n                                Location="%(location)s" />\n'
RESPONSE = '<samlp:Response\n  xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"\n  xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"\n  ID="%(id)s"\n  InResponseTo="%(in_response_to)s"\n  Version="2.0"\n  IssueInstant="%(issue_instant)s"\n  Destination="%(destination)s">\n    <saml:Issuer>%(entity_id)s</saml:Issuer>\n    <samlp:Status xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">\n        <samlp:StatusCode\n          xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"\n          Value="%(status)s">\n        </samlp:StatusCode>\n    </samlp:Status>\n    <saml:Assertion\n        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n        xmlns:xs="http://www.w3.org/2001/XMLSchema"\n        Version="2.0"\n        ID="%(assertion_id)s"\n        IssueInstant="%(issue_instant)s">\n        <saml:Issuer>%(entity_id)s</saml:Issuer>\n        <saml:Subject>\n            <saml:NameID\n              NameQualifier="%(entity_id)s"\n              SPNameQualifier="%(requester)s"\n              Format="%(name_id_policy)s">%(name_id)s</saml:NameID>\n            <saml:SubjectConfirmation Method="%(cm)s">\n                <saml:SubjectConfirmationData\n                  NotOnOrAfter="%(not_after)s"\n                  InResponseTo="%(in_response_to)s"\n                  Recipient="%(destination)s">\n                </saml:SubjectConfirmationData>\n            </saml:SubjectConfirmation>\n        </saml:Subject>\n        <saml:Conditions NotBefore="%(not_before)s" NotOnOrAfter="%(not_after)s">\n            <saml:AudienceRestriction>\n                <saml:Audience>%(requester)s</saml:Audience>\n            </saml:AudienceRestriction>\n        </saml:Conditions>\n        <saml:AuthnStatement\n          AuthnInstant="%(issue_instant)s"\n          SessionIndex="%(session_index)s"\n          SessionNotOnOrAfter="%(not_after)s">\n%(authn_context)s\n        </saml:AuthnStatement>\n        <saml:AttributeStatement>\n%(attributes)s\n        </saml:AttributeStatement>\n    </saml:Assertion>\n</samlp:Response>'

onelogin.saml2.xml_utils module

OneLogin_Saml2_XML class

Auxiliary class of SAML Python Toolkit.

class onelogin.saml2.xml_utils.OneLogin_Saml2_XML[source]

Bases: object

static cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None)[source]

Keeps the xmlns:xs namespace intact when etree.cleanup_namespaces is invoked. :param tree_or_element: An XML tree or element :type tree_or_element: etree.Element :param top_nsmap: A mapping from namespace prefixes to namespace URIs :type top_nsmap: dict :param keep_ns_prefixes: List of prefixes that should not be removed as part of the cleanup :type keep_ns_prefixes: list :returns: An XML tree or element :rtype: etree.Element

static dump(elem, pretty_print=True, with_tail=True)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

static element_text(node)[source]
static extract_tag_text(xml, tagname)[source]
static make_child(_parent, _tag, attrib=None, nsmap=None, **_extra)

SubElement(_parent, _tag, attrib=None, nsmap=None, **_extra)

Subelement factory. This function creates an element instance, and appends it to an existing element.

static make_root(_tag, attrib=None, nsmap=None, **_extra)

Element(_tag, attrib=None, nsmap=None, **_extra)

Element factory. This function returns an object implementing the Element interface.

Also look at the _Element.makeelement() and _BaseParser.makeelement() methods, which provide a faster way to create an Element within a specific document or parser context.

static query(dom, query, context=None, tagid=None)[source]

Extracts nodes that match the query from the Element

Parameters:
  • dom – The root of the lxml objet

  • query (String) – Xpath Expresion

  • context – Context Node

  • tagid – Tag ID

Type:

Element

Type:

string

Type:

DOMElement

Returns:

The queried nodes

Return type:

list

static to_etree(xml)[source]

Parses an XML document or fragment from a string. :param xml: the string to parse :type xml: str|bytes|xml.dom.minidom.Document|etree.Element :returns: the root node :rtype: OneLogin_Saml2_XML._element_class

static to_string(xml, **kwargs)[source]

Serialize an element to an encoded string representation of its XML tree. :param xml: The root node :type xml: str|bytes|xml.dom.minidom.Document|etree.Element :returns: string representation of xml :rtype: string

static validate_xml(xml, schema, debug=False)[source]

Validates a xml against a schema :param xml: The xml that will be validated :type xml: str|bytes|xml.dom.minidom.Document|etree.Element :param schema: The schema :type schema: string :param debug: If debug is active, the parse-errors will be showed :type debug: bool :returns: Error code or the DomDocument of the xml :rtype: xml.dom.minidom.Document

onelogin.saml2.xmlparser module

lxml.etree protection

exception onelogin.saml2.xmlparser.DTDForbidden(name, sysid, pubid)[source]

Bases: ValueError

Document type definition is forbidden

exception onelogin.saml2.xmlparser.EntitiesForbidden(name, value, base, sysid, pubid, notation_name)[source]

Bases: ValueError

Entity definition is forbidden

class onelogin.saml2.xmlparser.GlobalParserTLS[source]

Bases: _local

Thread local context for custom parser instances

createDefaultParser()[source]
element_class

alias of RestrictedElement

getDefaultParser()[source]
parser_config = {'huge_tree': False, 'no_network': True, 'remove_comments': True, 'remove_pis': True, 'resolve_entities': False}
setDefaultParser(parser)[source]
exception onelogin.saml2.xmlparser.NotSupportedError[source]

Bases: ValueError

The operation is not supported

class onelogin.saml2.xmlparser.RestrictedElement[source]

Bases: ElementBase

A restricted Element class that filters out instances of some classes

blacklist = (<class 'lxml.etree._Entity'>, <class 'lxml.etree._ProcessingInstruction'>, <class 'lxml.etree._Comment'>)
getchildren(self)[source]

Returns all direct children. The elements are returned in document order.

Deprecated:

Note that this method has been deprecated as of ElementTree 1.3 and lxml 2.0. New code should use list(element) or simply iterate over elements.

getiterator(self, tag=None, *tags)[source]

Returns a sequence or iterator of all elements in the subtree in document order (depth first pre-order), starting with this element.

Can be restricted to find only elements with specific tags, see iter.

Deprecated:

Note that this method is deprecated as of ElementTree 1.3 and lxml 2.0. It returns an iterator in lxml, which diverges from the original ElementTree behaviour. If you want an efficient iterator, use the element.iter() method instead. You should only use this method in new code if you require backwards compatibility with older versions of lxml or ElementTree.

iter(self, tag=None, *tags)[source]

Iterate over all elements in the subtree in document order (depth first pre-order), starting with this element.

Can be restricted to find only elements with specific tags: pass "{ns}localname" as tag. Either or both of ns and localname can be * for a wildcard; ns can be empty for no namespace. "localname" is equivalent to "{}localname" (i.e. no namespace) but "*" is "{*}*" (any or no namespace), not "{}*".

You can also pass the Element, Comment, ProcessingInstruction and Entity factory functions to look only for the specific element type.

Passing multiple tags (or a sequence of tags) instead of a single tag will let the iterator return all elements matching any of these tags, in document order.

iterchildren(self, tag=None, *tags, reversed=False)[source]

Iterate over the children of this element.

As opposed to using normal iteration on this element, the returned elements can be reversed with the ‘reversed’ keyword and restricted to find only elements with specific tags, see iter.

iterdescendants(self, tag=None, *tags)[source]

Iterate over the descendants of this element in document order.

As opposed to el.iter(), this iterator does not yield the element itself. The returned elements can be restricted to find only elements with specific tags, see iter.

itersiblings(self, tag=None, *tags, preceding=False)[source]

Iterate over the following or preceding siblings of this element.

The direction is determined by the ‘preceding’ keyword which defaults to False, i.e. forward iteration over the following siblings. When True, the iterator yields the preceding siblings in reverse document order, i.e. starting right before the current element and going backwards.

Can be restricted to find only elements with specific tags, see iter.

onelogin.saml2.xmlparser.XML(text, parser=None, base_url=None, forbid_dtd=True, forbid_entities=True)
onelogin.saml2.xmlparser.check_docinfo(elementtree, forbid_dtd=False, forbid_entities=True)[source]

Check docinfo of an element tree for DTD and entity declarations The check for entity declarations needs lxml 3 or newer. lxml 2.x does not support dtd.iterentities().

onelogin.saml2.xmlparser.fromstring(text, parser=None, base_url=None, forbid_dtd=True, forbid_entities=True)[source]
onelogin.saml2.xmlparser.getDefaultParser()
onelogin.saml2.xmlparser.iterparse(*args, **kwargs)[source]
onelogin.saml2.xmlparser.parse(source, parser=None, base_url=None, forbid_dtd=True, forbid_entities=True)[source]

Module contents

Add SAML support to your Python softwares using this library.

SAML Python toolkit let you build a SP (Service Provider) over your Python application and connect it to any IdP (Identity Provider).

Supports:

  • SSO and SLO (SP-Initiated and IdP-Initiated).

  • Assertion and nameId encryption.

  • Assertion signature.

  • Message signature: AuthNRequest, LogoutRequest, LogoutResponses.

  • Enable an Assertion Consumer Service endpoint.

  • Enable a Single Logout Service endpoint.

  • Publish the SP metadata (which can be signed).