onelogin.saml2 package¶
Submodules¶
onelogin.saml2.auth module¶
OneLogin_Saml2_Auth class
MIT License
Main class of 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:
objectThis 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).
-
build_request_signature(saml_request, relay_state, sign_algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1')[source]¶ Builds the Signature of the SAML Request.
Parameters: - saml_request (string) – The SAML Request
- relay_state (string) – The target URL the user should be redirected to
- sign_algorithm (string) – Signature algorithm method
-
build_response_signature(saml_response, relay_state, sign_algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1')[source]¶ Builds the Signature of the SAML Response. :param saml_request: The SAML Response :type saml_request: string
Parameters: - relay_state (string) – The target URL the user should be redirected to
- sign_algorithm (string) – Signature algorithm method
-
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_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 Return type: string|None
-
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 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 IdP SLO URL.
Returns: An URL, the SLO endpoint of the IdP Return type: string
-
get_sso_url()[source]¶ Gets the IdP 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
-
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
-
onelogin.saml2.authn_request module¶
OneLogin_Saml2_Authn_Request class
MIT License
AuthNRequest class of 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:
objectThis class handles an AuthNRequest. It builds an AuthNRequest object.
onelogin.saml2.constants module¶
OneLogin_Saml2_Constants class
MIT License
Constants class of Python Toolkit.
-
class
onelogin.saml2.constants.OneLogin_Saml2_Constants[source]¶ Bases:
objectThis class defines all the constants that will be used in the 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_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'¶
-
XML= 'http://www.w3.org/XML/1998/namespace'¶
-
XSI= 'http://www.w3.org/2001/XMLSchema-instance'¶
-
onelogin.saml2.errors module¶
OneLogin_Saml2_Error class
MIT License
Error class of 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:
exceptions.ExceptionThis 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:
exceptions.ExceptionThis 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
MIT License
Metadata class of Python Toolkit.
-
class
onelogin.saml2.idp_metadata_parser.OneLogin_Saml2_IdPMetadataParser[source]¶ Bases:
objectA 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.
-
static
get_metadata(url, validate_cert=True)[source]¶ Gets the metadata XML from the provided URL
Parameters: - url (string) – Url where the XML of the Identity Provider Metadata is published.
- validate_cert (bool) – If the url uses https schema, that flag enables or not the verification of the associated certificate.
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
Parameters: - settings (dict) – Current settings dict data
- new_metadata_settings (dict) – Settings to be merged (extracted from IdP metadata after parsing)
Returns: merged settings
Return type: dict
-
static
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]¶ Parse the Identity Provider metadata and return a dict with extracted data.
If there are multiple <IDPSSODescriptor> tags, parse only the first.
Parse only those SSO endpoints with the same binding as given by the required_sso_binding parameter.
Parse 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
-
static
parse_remote(url, validate_cert=True, entity_id=None, **kwargs)[source]¶ Gets the metadata XML from the provided URL and parse it, returning a dict with extracted data
Parameters: - url (string) – Url where the XML of the Identity Provider Metadata is published.
- 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.
Returns: settings dict with extracted data
Return type: dict
-
static
onelogin.saml2.logout_request module¶
OneLogin_Saml2_Logout_Request class
MIT License
Logout Request class of 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:
objectThis 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
-
static
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
-
static
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
-
static
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
-
static
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
-
static
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 Value :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
-
static
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 :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean :return: If the Logout Request is or not valid :rtype: boolean
-
onelogin.saml2.logout_response module¶
OneLogin_Saml2_Logout_Response class
MIT License
Logout Response class of Python Toolkit.
-
class
onelogin.saml2.logout_response.OneLogin_Saml2_Logout_Response(settings, response=None)[source]¶ Bases:
objectThis class handles a Logout Response. It Builds or parses a Logout Response object and validates it.
-
build(in_response_to)[source]¶ Creates a Logout Response object. :param in_response_to: InResponseTo value for the Logout Response. :type in_response_to: 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 the Logout Response defated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Response maybe deflated and base64 encoded :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 :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean :return: Returns if the SAML LogoutResponse is or not valid :rtype: boolean
-
onelogin.saml2.metadata module¶
OneLogin_Saml2_Metadata class
MIT License
Metadata class of Python Toolkit.
-
class
onelogin.saml2.metadata.OneLogin_Saml2_Metadata[source]¶ Bases:
objectA class that contains methods related to the metadata of the SP
-
TIME_CACHED= 604800¶
-
TIME_VALID= 172800¶
-
static
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
-
static
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
MIT License
SAML Response class of Python Toolkit.
-
class
onelogin.saml2.response.OneLogin_Saml2_Response(settings, response)[source]¶ Bases:
objectThis 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_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_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
-
onelogin.saml2.settings module¶
OneLogin_Saml2_Settings class
MIT License
Setting class of Python Toolkit.
-
class
onelogin.saml2.settings.OneLogin_Saml2_Settings(settings=None, custom_base_path=None, sp_validation_only=False)[source]¶ Bases:
objectHandles the settings of the Python toolkits.
-
check_idp_settings(settings)[source]¶ Checks the IdP settings info.
Parameters: settings (dict) – Dict with settings data Returns: Errors found on the IdP settings data Return type: 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 Return type: boolean
-
check_sp_settings(settings)[source]¶ Checks the SP settings info.
Parameters: settings (dict) – Dict with settings data Returns: Errors found on the SP settings data Return type: list
-
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 Return type: string
-
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_sp_cert()[source]¶ Returns the x509 public cert of the SP.
Returns: SP public cert Return type: 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 Return type: string or None
-
get_sp_key()[source]¶ Returns the x509 private key of the SP.
Returns: SP private key Return type: string or None
-
get_sp_metadata()[source]¶ Gets the SP metadata. The XML representation.
Returns: SP metadata (xml) Return type: 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
-
-
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
MIT License
Auxiliary class of Python Toolkit.
-
class
onelogin.saml2.utils.OneLogin_Saml2_Utils[source]¶ Bases:
objectAuxiliary 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= <_sre.SRE_Pattern object>¶
-
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
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)[source]¶ base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :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
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: Formatted 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
Type: string
Returns: DOMElement | XMLSec nameID
Return 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_encoded_parameter(get_data, name, default=None, lowercase_urlencoding=False)[source]¶ Return a URL encoded get parameter value Prefer to extract the original encoded value directly from query_string since URL encoding is not canonical. 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)
-
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.
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
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: time – 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
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 – Xpath Expresion
- context – Context Node
- tagid – Tag ID
Type: Element
Type: string
Type: DOMElement
Type: string
Returns: The queried nodes
Return type: list
-
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
validate_binary_sign(*args, **kwargs)[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
- raise_exceptions (Boolean) – Whether to return false on failure or raise an exception
Type: string
Type: string
Type: string
Type: string
Type: bool
-
static
validate_metadata_sign(*args, **kwargs)[source]¶ Validates a signature of a EntityDescriptor.
Parameters: - xml – The element we should validate
- cert – The pubic 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(*args, **kwargs)[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(*args, **kwargs)[source]¶ Validates a signature (Message or Assertion).
Parameters: - xml – The element we should validate
- cert – The pubic 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
-
static
validate_xml(xml, schema, debug=False)[source]¶ Validates a xml against a schema :param xml: The xml that will be validated :type: string|DomDocument :param schema: The schema :type: string :param debug: If debug is active, the parse-errors will be showed :type: bool :returns: Error code or the DomDocument of the xml :rtype: string
-
onelogin.saml2.xmlparser module¶
lxml.etree protection
-
class
onelogin.saml2.xmlparser.GlobalParserTLS[source]¶ Bases:
thread._localThread local context for custom parser instances
-
element_class¶ alias of
RestrictedElement
-
parser_config= {'huge_tree': False, 'no_network': True, 'remove_comments': True, 'remove_pis': True, 'resolve_entities': False}¶
-
-
class
onelogin.saml2.xmlparser.RestrictedElement[source]¶ Bases:
lxml.etree.ElementBaseA restricted Element class that filters out instances of some classes
-
blacklist= (<type 'lxml.etree._Entity'>, <type 'lxml.etree._ProcessingInstruction'>, <type '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 ofnsandlocalnamecan be*for a wildcard;nscan 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().
Module contents¶
Copyright (c) 2010-2022 OneLogin, Inc. Copyright (c) 2023 IAM Digital Services, SL.
MIT License
Add SAML support to your Python softwares using this library. Forget those complicated libraries and use that open source 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).