OneLogin saml2 Module — OneLogin SAML Python library classes and methods

### Navigation

- index
- modules |
- previous |
- OneLogin SAML Python library classes and methods »

# OneLogin saml2 Module

## `auth` Class

class `onelogin.saml2.auth.` `OneLogin_Saml2_Auth`(request_data, old_settings=None)

  Bases: `object`

  `build_request_signature`(saml_request, relay_state)

    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

  `build_response_signature`(saml_response, relay_state)

    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

  `get_attribute`(name)

    Returns the requested SAML attribute.

    Parameters: | name (string) – Name of the attribute
    Returns: | Attribute value if exists or None
    Return type: | string

  `get_attributes`()

    Returns the set of SAML attributes.

    Returns: | SAML attributes
    Return type: | dict

  `get_errors`()

    Returns a list with code errors if something went wrong

    Returns: | List of errors
    Return type: | list

  `get_last_error_reason`()

    Returns the reason for the last error

    Returns: | Error
    Return type: | string

  `get_nameid`()

    Returns the nameID.

    Returns: | NameID
    Return type: | string

  `get_settings`()

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

  `get_slo_url`()

    Gets the SLO url.

    Returns: | An URL, the SLO endpoint of the IdP
    Return type: | string

  `get_sso_url`()

    Gets the SSO url.

    Returns: | An URL, the SSO endpoint of the IdP
    Return type: | string

  `is_authenticated`()

    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)

    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 AuthNReuqest will set the ForceAuthn='true'. is_passive (bool) – Optional argument. When true the AuthNReuqest will set the Ispassive='true'.
    Returns: | Redirection url

  `logout`(return_to=None, name_id=None, session_index=None)

    Initiates the SLO process.

    Parameters: | return_to (string) – Optional argument. The target URL the user should be redirected to after logout. name_id (string) – Optional argument. The NameID that will be set in the LogoutRequest. session_index (string) – Optional argument. SessionIndex that identifies the session of the user.
    Returns: | Redirection url

  `process_response`(request_id=None)

    Process the SAML Response sent by the IdP.

    Parameters: | request_id (string) – Is an optional argumen. 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)

    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={})

    Redirects the user to the url past 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

  `set_strict`(value)

    Set the strict mode active/disable

    Parameters: | value (bool) –

## `authn_request` Class

class `onelogin.saml2.authn_request.` `OneLogin_Saml2_Authn_Request`(settings, force_authn=False, is_passive=False)
  `get_request`()

    Returns unsigned AuthnRequest. :return: Unsigned AuthnRequest :rtype: str object

## `constants` Class

class `onelogin.saml2.constants.` `OneLogin_Saml2_Constants`
  `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_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'
  `ALOWED_CLOCK_DRIFT` = 180
  `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'
  `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_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` = {'xenc': 'http://www.w3.org/2001/04/xmlenc#', 'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol', 'ds': 'http://www.w3.org/2000/09/xmldsig#', 'saml': 'urn:oasis:names:tc:SAML:2.0:assertion'}
  `NS_DS` = 'http://www.w3.org/2000/09/xmldsig#'
  `NS_MD` = 'urn:oasis:names:tc:SAML:2.0:metadata'
  `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_SHA1` = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
  `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'

## `errors` Class

exception `onelogin.saml2.errors.` `OneLogin_Saml2_Error`(message, code=0, errors=None)

  Bases: `exceptions.Exception`

  `METADATA_SP_INVALID` = 3
  `PRIVATE_KEY_FILE_NOT_FOUND` = 7
  `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

## `logout_request` Class

class `onelogin.saml2.logout_request.` `OneLogin_Saml2_Logout_Request`(settings, request=None, name_id=None, session_index=None)
  static `get_id`(request)

    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)

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

  static `get_name_id`(request, key=None)

    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_name_id_data`(request, key=None)

    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

  `get_request`()

    Returns the Logout Request defated, base64encoded :return: Deflated base64 encoded Logout Request :rtype: str object

  static `get_session_indexes`(request)

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

  static `is_valid`(settings, request, get_data, debug=False)

    Checks if the Logout Request recieved is valid :param settings: Settings :type settings: OneLogin_Saml2_Settings :param request: Logout Request Message :type request: string|DOMDocument :return: If the Logout Request is or not valid :rtype: boolean

  `get_error`()

    After execute a validation process, if fails this method returns the cause :rtype: str object

## `logout_response` Class

class `onelogin.saml2.logout_response.` `OneLogin_Saml2_Logout_Response`(settings, response=None)
  `build`(in_response_to)

    Creates a Logout Response object. :param in_response_to: InResponseTo value for the Logout Response. :type in_response_to: string

  `get_issuer`()

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

  `get_response`()

    Returns a Logout Response object. :return: Logout Response deflated and base64 encoded :rtype: string

  `get_status`()

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

  `is_valid`(request_data, request_id=None)

    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 :return: Returns if the SAML LogoutResponse is or not valid :rtype: boolean

  `get_error`()

    After execute a validation process, if fails this method returns the cause :rtype: str object

## `metadata` Class

class `onelogin.saml2.metadata.` `OneLogin_Saml2_Metadata`
  `TIME_CACHED` = 604800
  `TIME_VALID` = 172800
  static `add_x509_key_descriptors`(metadata, cert)

    Add the x509 descriptors (sign/encriptation to the metadata The same cert will be used for sign/encrypt

    Parameters: | metadata (string) – SAML Metadata XML cert (string) – x509 cert
    Returns: | Metadata with KeyDescriptors
    Return type: | string

  static `builder`(sp, authnsign=False, wsign=False, valid_until=None, cache_duration=None, contacts=None, organization=None)

    Build the metadata of the SP

    Parameters: | sp (string) – The SP data authnsign (string) – authnRequestsSigned attribute wsign (string) – wantAssertionsSigned attribute valid_until (DateTime) – Metadata’s valid time cache_duration (Timestamp) – Duration of the cache in seconds contacts (dict) – Contacts info organization (dict) – Organization ingo

  static `sign_metadata`(metadata, key, cert)

    Sign the metadata with the key/cert provided

    Parameters: | metadata (string) – SAML Metadata XML key (string) – x509 key cert (string) – x509 cert
    Returns: | Signed Metadata
    Return type: | string

## `response` Class

class `onelogin.saml2.response.` `OneLogin_Saml2_Response`(settings, response)

  Bases: `object`

  `check_status`()

    Check if the status of the response is success or not

    Raises : | Exception. If the status is not success

  `get_attributes`()

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

  `get_audiences`()

    Gets the audiences

    Returns: | The valid audiences for the SAML Response
    Return type: | list

  `get_issuers`()

    Gets the issuers (from message and from assertion)

    Returns: | The issuers
    Return type: | list

  `get_nameid`()

    Gets the NameID provided by the SAML Response from the IdP

    Returns: | NameID (value)
    Return type: | string

  `get_nameid_data`()

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

    Returns: | Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
    Return type: | dict

  `get_session_index`()

    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`()

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

    Returns: | The SessionNotOnOrAfter value
    Return type: | time|None

  `is_valid`(request_data, request_id=None)

    Constructs the response object.

    Parameters: | request_id (string) – Optional argument. The ID of the AuthNRequest sent by this SP to the IdP
    Returns: | True if the SAML Response is valid, False if not
    Return type: | bool

  `validate_num_assertions`()

    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_timestamps`()

    Verifies that the document is valid according to Conditions Element

    Returns: | True if the condition is valid, False otherwise
    Return type: | bool

## `settings` Class

class `onelogin.saml2.settings.` `OneLogin_Saml2_Settings`(settings=None, custom_base_path=None)
  `check_settings`(settings)

    Checks the settings info.

    Parameters: | settings (dict) – Dict with settings data
    Returns: | Errors found on the settings data
    Return type: | list

  `check_sp_certs`()

    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

  `format_idp_cert`()

    Formats the IdP cert.

  `get_base_path`()

    Returns base path

    Returns: | The base toolkit folder path
    Return type: | string

  `get_cert_path`()

    Returns cert path

    Returns: | The cert folder path
    Return type: | string

  `get_contacts`()

    Gets contact data.

    Returns: | Contacts info
    Return type: | dict

  `get_errors`()

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

    Returns: | Errors
    Return type: | list

  `get_ext_lib_path`()

    Returns external lib path

    Returns: | The external library folder path
    Return type: | string

  `get_idp_data`()

    Gets the IdP data.

    Returns: | IdP info
    Return type: | dict

  `get_lib_path`()

    Returns lib path

    Returns: | The library folder path
    Return type: | string

  `get_organization`()

    Gets organization data.

    Returns: | Organization info
    Return type: | dict

  `get_schemas_path`()

    Returns schema path

    Returns: | The schema folder path
    Return type: | string

  `get_security_data`()

    Gets security data.

    Returns: | Security info
    Return type: | dict

  `get_sp_cert`()

    Returns the x509 public cert of the SP.

    Returns: | SP public cert
    Return type: | string

  `get_sp_data`()

    Gets the SP data.

    Returns: | SP info
    Return type: | dict

  `get_sp_key`()

    Returns the x509 private key of the SP.

    Returns: | SP private key
    Return type: | string

  `get_sp_metadata`()

    Gets the SP metadata. The XML representation.

    Returns: | SP metadata (xml)
    Return type: | string

  `is_debug_active`()

    Returns if the debug is active.

    Returns: | Debug parameter
    Return type: | boolean

  `is_strict`()

    Returns if the ‘strict’ mode is active.

    Returns: | Strict parameter
    Return type: | boolean

  `set_strict`(value)

    Activates or deactivates the strict mode.

    Parameters: | xml (boolean) – Strict parameter

  `validate_metadata`(xml)

    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)

## `utils` Class

class `onelogin.saml2.utils.` `OneLogin_Saml2_Utils`
  static `add_sign`(xml, key, cert)

    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
    Type : | string | Document
    Type : | string
    Type : | string

  static `calculate_x509_fingerprint`(x509_cert)

    Calculates the fingerprint of a x509cert.

    Parameters: | x509_cert – x509 cert
    Type : | string
    Returns: | Formated fingerprint
    Return type: | string

  static `decode_base64_and_inflate`(value)

    base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :return: the string after decoding and inflating

  static `decrypt_element`(encrypted_data, enc_ctx)

    Decrypts an encrypted element.

    Parameters: | encrypted_data – The encrypted data. enc_ctx – The encryption context.
    Type : | DOMElement
    Type : | Encryption Context
    Returns: | The decrypted element.
    Return type: | DOMElement

  static `deflate_and_base64_encode`(value)

    Deflates and the base64 encodes a string :param value: The string to deflate and encode :return: The deflated and encoded string

  static `delete_local_session`(callback=None)

    Deletes the local session.

  static `format_cert`(cert, heads=True)

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

    Parameters: | cert – A x509 unformated cert heads – True if we want to include head and footer
    Type : | string
    Type : | boolean
    Returns: | Formated cert
    Return type: | string

  static `format_finger_print`(fingerprint)

    Formates a fingerprint.

    Parameters: | fingerprint – fingerprint
    Type : | string
    Returns: | Formated fingerprint
    Return type: | string

  static `generate_name_id`(value, sp_nq, sp_format, key=None)

    Generates a nameID.

    Parameters: | value – fingerprint sp_nq – SP Name Qualifier sp_format – SP Format key – SP Key to encrypt the nameID
    Type : | string
    Type : | string
    Type : | string
    Type : | string
    Returns: | DOMElement | XMLSec nameID
    Return type: | string

  static `generate_unique_id`()

    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)

    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)

    Returns the current host.

    Parameters: | request_data – The request as a dict
    Type : | dict
    Returns: | The current host
    Return type: | string

  static `get_self_url`(request_data)

    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)

    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)

    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)

    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)

    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 `parse_SAML_to_time`(timestr)

    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)

    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)

    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)

    Extracts nodes that match the query from the Element

    Parameters: | dom – The root of the lxml objet query – Xpath Expresion context – Context Node
    Type : | Element
    Type : | string
    Type : | DOMElement
    Returns: | The queried nodes
    Return type: | list

  static `redirect`(url, parameters={}, request_data={})

    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_sign`(xml, cert=None, fingerprint=None)

    Validates a signature (Message or Assertion).

    Parameters: | xml – The element we should validate cert – The pubic cert fingerprint – The fingerprint of the public cert
    Type : | string | Document
    Type : | string
    Type : | string

  static `validate_xml`(xml, schema, debug=False)
  static `write_temp_file`(content)

    Writes some content into a temporary file and returns it.

    Parameters: | content – The file content
    Type : | string
    Returns: | The temporary file
    Return type: | file-like object

### Navigation

- index
- modules |
- previous |
- OneLogin SAML Python library classes and methods »