CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python3-saml

Comprehensive SAML 2.0 toolkit for Python applications enabling SSO and SLO functionality with Service Provider support

Pending
Overview
Eval results
Files

authentication.mddocs/

Authentication and SSO/SLO

Core SAML authentication functionality providing Single Sign-On (SSO) and Single Logout (SLO) capabilities. The OneLogin_Saml2_Auth class serves as the primary interface for all SAML operations, managing the complete authentication workflow from initiation to completion.

Capabilities

SAML Auth Instance Initialization

Creates and configures a SAML Service Provider authentication instance with request data and settings.

class OneLogin_Saml2_Auth:
    def __init__(self, request_data: dict, old_settings: dict = None, custom_base_path: str = None):
        """
        Initialize the SP SAML instance.
        
        Parameters:
        - request_data: HTTP request information structure
        - old_settings: SAML configuration settings (dict or OneLogin_Saml2_Settings)
        - custom_base_path: Path to settings file and cert folder
        """

Request Data Structure:

request_data = {
    'https': 'on' | 'off',  # Whether HTTPS is used
    'http_host': 'example.com',  # HTTP host
    'script_name': '/path',  # Script path
    'get_data': {},  # GET parameters
    'post_data': {},  # POST parameters
    'query_string': '...',  # Optional: raw query string
    'lowercase_urlencoding': True,  # Optional: ADFS compatibility
    'validate_signature_from_qs': True  # Optional: signature validation method
}

Single Sign-On (SSO) Initiation

Initiates the SAML authentication process by redirecting users to the Identity Provider for authentication.

def login(self, return_to: str = None, force_authn: bool = False, is_passive: bool = False, set_nameid_policy: bool = True, name_id_value_req: str = None) -> str:
    """
    Initiate SSO process by building an authentication request.
    
    Parameters:
    - return_to: Target URL for redirection after login
    - force_authn: Forces authentication even if user has active session
    - is_passive: Sets IsPassive='true' for transparent authentication attempts
    - set_nameid_policy: Whether to include NameIDPolicy element
    - name_id_value_req: Specific subject that should be authenticated
    
    Returns:
    Redirection URL to IdP for authentication
    """

Usage Example:

# Basic SSO initiation
auth = OneLogin_Saml2_Auth(request_data, settings)
sso_url = auth.login()

# SSO with return URL and forced authentication
sso_url = auth.login(
    return_to="https://myapp.com/dashboard",
    force_authn=True
)

SAML Response Processing

Processes SAML Response sent by the Identity Provider after user authentication, validating the response and extracting user information.

def process_response(self, request_id: str = None) -> None:
    """
    Process SAML Response from IdP after authentication.
    
    Parameters:
    - request_id: ID of the AuthNRequest sent by this SP
    
    Raises:
    - OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND: No SAMLResponse in POST data
    """

Usage Example:

# Process SAML response in ACS endpoint
auth = OneLogin_Saml2_Auth(request_data, settings)
auth.process_response()

if auth.is_authenticated():
    # Authentication successful
    user_attributes = auth.get_attributes()
    user_id = auth.get_nameid()
    session_index = auth.get_session_index()
else:
    # Authentication failed
    errors = auth.get_errors()
    error_reason = auth.get_last_error_reason()

Single Logout (SLO) Initiation

Initiates the SAML Single Logout process, redirecting users to the Identity Provider for session termination.

def logout(self, return_to: str = None, name_id: str = None, session_index: str = None, nq: str = None, name_id_format: str = None, spnq: str = None) -> str:
    """
    Initiate SLO process by building a logout request.
    
    Parameters:
    - return_to: Target URL for redirection after logout
    - name_id: NameID for the LogoutRequest
    - session_index: SessionIndex identifying user session
    - nq: IdP Name Qualifier
    - name_id_format: NameID Format for LogoutRequest
    - spnq: SP Name Qualifier
    
    Returns:
    Redirection URL to IdP for logout
    
    Raises:
    - OneLogin_Saml2_Error.SAML_SINGLE_LOGOUT_NOT_SUPPORTED: IdP doesn't support SLO
    """

SAML Logout Processing

Processes SAML Logout Response or Logout Request sent by the Identity Provider during the SLO workflow.

def process_slo(self, keep_local_session: bool = False, request_id: str = None, delete_session_cb: callable = None) -> str:
    """
    Process SAML Logout Response or Logout Request from IdP.
    
    Parameters:
    - keep_local_session: Whether to preserve local session
    - request_id: ID of LogoutRequest sent by this SP
    - delete_session_cb: Callback function to delete session
    
    Returns:
    Redirection URL or None
    
    Raises:
    - OneLogin_Saml2_Error.SAML_LOGOUTMESSAGE_NOT_FOUND: No logout message found
    """

Usage Example:

# Process logout in SLS endpoint
auth = OneLogin_Saml2_Auth(request_data, settings)

def clear_user_session():
    # Custom session cleanup logic
    session.clear()

redirect_url = auth.process_slo(delete_session_cb=clear_user_session)
if redirect_url:
    # Redirect user to continue logout flow
    pass

Authentication Status Checking

Verifies if the user has been successfully authenticated through the SAML process.

def is_authenticated(self) -> bool:
    """
    Check if user is authenticated.
    
    Returns:
    True if authenticated, False otherwise
    """

User Attribute Retrieval

Extracts user attributes from SAML assertions for application use.

def get_attributes(self) -> dict:
    """
    Get all SAML attributes from assertion.
    
    Returns:
    Dictionary mapping attribute names to lists of values
    """

def get_friendlyname_attributes(self) -> dict:
    """
    Get SAML attributes indexed by FriendlyName.
    
    Returns:
    Dictionary mapping FriendlyNames to lists of values
    """

def get_attribute(self, name: str) -> list:
    """
    Get specific SAML attribute by name.
    
    Parameters:
    - name: Attribute name to retrieve
    
    Returns:
    List of attribute values or None
    """

def get_friendlyname_attribute(self, friendlyname: str) -> list:
    """
    Get specific SAML attribute by FriendlyName.
    
    Parameters:
    - friendlyname: FriendlyName to search for
    
    Returns:
    List of attribute values or None
    """

NameID and Session Information

Retrieves user identification and session details from SAML assertions.

def get_nameid(self) -> str:
    """
    Get NameID from SAML assertion.
    
    Returns:
    NameID string or None
    """

def get_nameid_format(self) -> str:
    """
    Get NameID Format from assertion.
    
    Returns:
    NameID Format string or None
    """

def get_nameid_nq(self) -> str:
    """
    Get NameID NameQualifier from assertion.
    
    Returns:
    NameID NameQualifier string or None
    """

def get_nameid_spnq(self) -> str:
    """
    Get NameID SP NameQualifier from assertion.
    
    Returns:
    NameID SP NameQualifier string or None
    """

def get_session_index(self) -> str:
    """
    Get SessionIndex from AuthnStatement.
    
    Returns:
    SessionIndex string
    """

def get_session_expiration(self) -> int:
    """
    Get SessionNotOnOrAfter from AuthnStatement.
    
    Returns:
    Unix/POSIX timestamp or None
    """

def get_last_assertion_not_on_or_after(self) -> int:
    """
    Get NotOnOrAfter value of valid SubjectConfirmationData node.
    
    Returns:
    Unix/POSIX timestamp or None
    """

def get_last_assertion_issue_instant(self) -> int:
    """
    Get IssueInstant of the last assertion processed.
    
    Returns:
    Unix/POSIX timestamp or None
    """

Error Handling

Provides comprehensive error information when SAML operations fail.

def get_errors(self) -> list:
    """
    Get list of error codes if something went wrong.
    
    Returns:
    List of error strings
    """

def get_last_error_reason(self) -> str:
    """
    Get reason for the last error.
    
    Returns:
    Error reason string or None
    """

URL and Redirection Management

Manages URLs for SAML endpoints and user redirection.

def get_sso_url(self) -> str:
    """
    Get SSO URL endpoint of the IdP.
    
    Returns:
    SSO URL string
    """

def get_slo_url(self) -> str:
    """
    Get SLO URL endpoint of the IdP.
    
    Returns:
    SLO URL string
    """

def redirect_to(self, url: str = None, parameters: dict = {}) -> str:
    """
    Generate redirection URL with optional parameters.
    
    Parameters:
    - url: Target URL for redirection
    - parameters: Extra parameters to pass in URL
    
    Returns:
    Redirection URL string
    """

Request and Response Information

Retrieves metadata about processed SAML messages.

def get_last_request_id(self) -> str:
    """
    Get ID of the last SAML request generated.
    
    Returns:
    Request ID string
    """

def get_last_message_id(self) -> str:
    """
    Get ID of the last SAML response processed.
    
    Returns:
    Message ID string
    """

def get_last_assertion_id(self) -> str:
    """
    Get ID of the last assertion processed.
    
    Returns:
    Assertion ID string
    """

def get_last_authn_contexts(self) -> list:
    """
    Get authentication contexts from last SAML Response.
    
    Returns:
    List of authentication context strings
    """

XML Message Access

Provides access to raw SAML XML messages for debugging and logging.

def get_last_response_xml(self, pretty_print_if_possible: bool = False) -> str:
    """
    Get raw XML of last SAML response or logout response.
    
    Parameters:
    - pretty_print_if_possible: Whether to format XML nicely
    
    Returns:
    SAML response XML string or None
    """

def get_last_request_xml(self) -> str:
    """
    Get raw XML sent in last SAML request.
    
    Returns:
    SAML request XML string or None
    """

Configuration Management

Methods for managing SAML settings and configuration state.

def get_settings(self) -> OneLogin_Saml2_Settings:
    """
    Get the current SAML settings object.
    
    Returns:
    OneLogin_Saml2_Settings object containing all SAML configuration
    """

def set_strict(self, value: bool) -> None:
    """
    Enable or disable strict validation mode.
    
    Parameters:
    - value: Whether to enable strict mode
    """

Digital Signature Management

Handles digital signatures for SAML message security.

def add_request_signature(self, request_data: dict, sign_algorithm: str = OneLogin_Saml2_Constants.RSA_SHA256) -> None:
    """
    Build signature for SAML requests.
    
    Parameters:
    - request_data: Request parameters to sign
    - sign_algorithm: Signature algorithm method
    """

def validate_request_signature(self, request_data: dict) -> bool:
    """
    Validate signature of SAML request.
    
    Parameters:
    - request_data: Request data to validate
    
    Returns:
    True if signature is valid, False otherwise
    """

Usage Patterns

Complete SSO Flow

# 1. Initiate SSO
auth = OneLogin_Saml2_Auth(request_data, settings)
if 'sso' in request.form:
    return redirect(auth.login())

# 2. Process response in ACS endpoint
elif 'SAMLResponse' in request.form:
    auth.process_response()
    if auth.is_authenticated():
        session['user_id'] = auth.get_nameid()
        session['attributes'] = auth.get_attributes()
        return redirect('/dashboard')
    else:
        return f"Authentication failed: {auth.get_errors()}"

Complete SLO Flow

# 1. Initiate logout
if 'slo' in request.form:
    return redirect(auth.logout())

# 2. Process logout in SLS endpoint
elif 'SAMLRequest' in request.form or 'SAMLResponse' in request.form:
    url = auth.process_slo(delete_session_cb=lambda: session.clear())
    if url:
        return redirect(url)
    else:
        return redirect('/logged_out')

Install with Tessl CLI

npx tessl i tessl/pypi-python3-saml

docs

authentication.md

configuration.md

index.md

message-processing.md

utilities.md

tile.json