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

configuration.mddocs/

Configuration and Settings

SAML configuration management including settings validation, metadata generation, certificate handling, and IdP metadata parsing. The configuration system provides comprehensive tools for setting up Service Provider configurations and integrating with Identity Providers.

Capabilities

SAML Settings Management

Core configuration class that handles SP (Service Provider), IdP (Identity Provider), and security settings with comprehensive validation and certificate management.

class OneLogin_Saml2_Settings:
    def __init__(self, settings: dict = None, custom_base_path: str = None, sp_validation_only: bool = False):
        """
        Initialize SAML settings.
        
        Parameters:
        - settings: SAML configuration dictionary
        - custom_base_path: Path to settings files and certificates
        - sp_validation_only: Skip IdP validation if True
        """

Settings Structure:

settings = {
    "strict": True,  # Enable strict validation
    "debug": False,  # Enable debug mode
    "sp": {
        "entityId": "https://sp.example.com/metadata/",
        "assertionConsumerService": {
            "url": "https://sp.example.com/acs",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
        },
        "singleLogoutService": {
            "url": "https://sp.example.com/sls", 
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "NameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
        "x509cert": "",  # SP certificate
        "privateKey": ""  # SP private key
    },
    "idp": {
        "entityId": "https://idp.example.com/metadata",
        "singleSignOnService": {
            "url": "https://idp.example.com/sso",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "singleLogoutService": {
            "url": "https://idp.example.com/slo",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "x509cert": "IdP Certificate"
    },
    "security": {
        "nameIdEncrypted": False,
        "authnRequestsSigned": False,
        "logoutRequestSigned": False,
        "wantMessagesSigned": False,
        "wantAssertionsSigned": False,
        "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
    }
}

Configuration Data Access

Methods to retrieve specific configuration sections and validate settings.

def get_sp_data(self) -> dict:
    """
    Get Service Provider configuration data.
    
    Returns:
    Dictionary containing SP configuration
    """

def get_idp_data(self) -> dict:
    """
    Get Identity Provider configuration data.
    
    Returns:
    Dictionary containing IdP configuration
    """

def get_security_data(self) -> dict:
    """
    Get security configuration data.
    
    Returns:
    Dictionary containing security settings
    """

def get_contacts(self) -> dict:
    """
    Get contact person data.
    
    Returns:
    Dictionary containing contact information
    """

def get_organization(self) -> dict:
    """
    Get organization data.
    
    Returns:
    Dictionary containing organization information
    """

Certificate Management

Handle X.509 certificates for SP and IdP cryptographic operations.

def get_sp_cert(self) -> str:
    """
    Get SP x509 public certificate.
    
    Returns:
    SP certificate string or None
    """

def get_sp_key(self) -> str:
    """
    Get SP x509 private key.
    
    Returns:
    SP private key string or None
    """

def get_sp_cert_new(self) -> str:
    """
    Get new SP certificate for cert rollover.
    
    Returns:
    New SP certificate string or None
    """

def get_idp_cert(self) -> str:
    """
    Get IdP x509 public certificate.
    
    Returns:
    IdP certificate string or None
    """

URL Configuration

Access to SAML endpoint URLs for SSO and SLO operations.

def get_idp_sso_url(self) -> str:
    """
    Get IdP Single Sign-On URL.
    
    Returns:
    SSO URL string
    """

def get_idp_slo_url(self) -> str:
    """
    Get IdP Single Logout URL.
    
    Returns:
    SLO URL string
    """

def get_idp_slo_response_url(self) -> str:
    """
    Get IdP SLO response URL.
    
    Returns:
    SLO response URL string
    """

Settings Validation

Comprehensive validation methods for SAML configuration components.

def check_settings(self, settings: dict) -> list:
    """
    Validate complete SAML settings.
    
    Parameters:
    - settings: Settings dictionary to validate
    
    Returns:
    List of validation error strings
    """

def check_idp_settings(self, settings: dict) -> list:
    """
    Validate IdP-specific settings.
    
    Parameters:
    - settings: Settings dictionary to validate
    
    Returns:
    List of IdP validation errors
    """

def check_sp_settings(self, settings: dict) -> list:
    """
    Validate SP-specific settings.
    
    Parameters:
    - settings: Settings dictionary to validate
    
    Returns:
    List of SP validation errors
    """

def check_sp_certs(self) -> bool:
    """
    Validate SP certificates exist and are valid.
    
    Returns:
    True if certificates are valid, False otherwise
    """

Metadata Generation

Generate and validate SAML metadata XML for Service Provider registration with Identity Providers.

def get_sp_metadata(self) -> str:
    """
    Generate SP metadata XML.
    
    Returns:
    Complete SP metadata XML string
    """

def validate_metadata(self, xml: str) -> list:
    """
    Validate SP metadata XML.
    
    Parameters:
    - xml: Metadata XML to validate
    
    Returns:
    List of validation error strings
    """

Configuration State Management

Control validation modes and debug settings.

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

def is_strict(self) -> bool:
    """
    Check if strict mode is active.
    
    Returns:
    True if strict mode is enabled
    """

def is_debug_active(self) -> bool:
    """
    Check if debug mode is active.
    
    Returns:
    True if debug mode is enabled
    """

def get_errors(self) -> list:
    """
    Get validation error list.
    
    Returns:
    List of validation error strings
    """

Path Management

Methods for accessing toolkit directory paths and configuration locations.

def get_base_path(self) -> str:
    """
    Get the base toolkit folder path.
    
    Returns:
    Absolute path to the base toolkit directory
    """

def get_cert_path(self) -> str:
    """
    Get the certificate folder path.
    
    Returns:
    Absolute path to the certificate directory
    """

def get_lib_path(self) -> str:
    """
    Get the library folder path.
    
    Returns:
    Absolute path to the library directory
    """

def get_schemas_path(self) -> str:
    """
    Get the schemas folder path.
    
    Returns:
    Absolute path to the XSD schemas directory
    """

SP Metadata Generation

Advanced metadata generation with certificate management, signing, and organizational information.

class OneLogin_Saml2_Metadata:
    @classmethod
    def builder(cls, sp: dict, authnsign: bool = False, wsign: bool = False, valid_until: str = None, cache_duration: int = None, contacts: dict = None, organization: dict = None) -> str:
        """
        Build complete SP metadata XML.
        
        Parameters:
        - sp: SP configuration data
        - authnsign: Whether AuthN requests are signed
        - wsign: Whether assertions should be signed
        - valid_until: Metadata expiry date
        - cache_duration: Cache duration in seconds
        - contacts: Contact person information
        - organization: Organization information
        
        Returns:
        Complete SP metadata XML string
        """

Certificate Metadata Management

Add X.509 certificates to metadata for key management and encryption.

@classmethod
def add_x509_key_descriptors(cls, metadata: str, cert: str = None, add_encryption: bool = True) -> str:
    """
    Add X.509 certificate descriptors to metadata.
    
    Parameters:
    - metadata: Existing metadata XML
    - cert: X.509 certificate to add
    - add_encryption: Whether to add encryption key descriptor
    
    Returns:
    Updated metadata XML with key descriptors
    """

Metadata Signing

Digitally sign metadata XML for enhanced security and trust.

@staticmethod
def sign_metadata(metadata: str, key: str, cert: str, sign_algorithm: str = OneLogin_Saml2_Constants.RSA_SHA256, digest_algorithm: str = OneLogin_Saml2_Constants.SHA256) -> str:
    """
    Sign metadata XML with provided key/certificate.
    
    Parameters:
    - metadata: SAML metadata XML to sign
    - key: X.509 private key for signing
    - cert: X.509 certificate for signing
    - sign_algorithm: Signature algorithm (default: RSA-SHA256)
    - digest_algorithm: Digest algorithm (default: SHA256)
    
    Returns:
    Signed metadata XML
    """

IdP Metadata Parsing

Parse Identity Provider metadata to automatically configure SAML settings.

class OneLogin_Saml2_IdPMetadataParser:
    @classmethod
    def get_metadata(cls, url: str, validate_cert: bool = True, timeout: int = None, headers: dict = None) -> str:
        """
        Retrieve IdP metadata XML from URL.
        
        Parameters:
        - url: URL where IdP metadata is published
        - validate_cert: Whether to validate HTTPS certificates
        - timeout: Request timeout in seconds  
        - headers: Additional HTTP headers
        
        Returns:
        Raw metadata XML string
        
        Raises:
        Exception if metadata is invalid or URL unreachable
        """

Remote Metadata Processing

Retrieve and parse remote IdP metadata in a single operation.

@classmethod
def parse_remote(cls, url: str, validate_cert: bool = True, entity_id: str = None, timeout: int = None, **kwargs) -> dict:
    """
    Retrieve and parse remote IdP metadata.
    
    Parameters:
    - url: IdP metadata URL
    - validate_cert: Certificate validation flag
    - entity_id: Specific entity ID for multi-entity metadata
    - timeout: Request timeout
    - **kwargs: Additional parameters passed to parse method
    
    Returns:
    Parsed settings dictionary
    """

Metadata XML Parsing

Parse IdP metadata XML and extract SAML configuration data.

@classmethod
def parse(cls, idp_metadata: str, required_sso_binding: str = OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT, required_slo_binding: str = OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT, entity_id: str = None) -> dict:
    """
    Parse IdP metadata XML and extract configuration.
    
    Parameters:
    - idp_metadata: IdP metadata XML
    - required_sso_binding: Required SSO binding (POST or REDIRECT)
    - required_slo_binding: Required SLO binding (POST or REDIRECT)
    - entity_id: Specific entity ID for multi-entity metadata
    
    Returns:
    Dictionary with extracted IdP settings
    """

Extracted Settings Structure:

{
    "idp": {
        "entityId": "https://idp.example.com/metadata",
        "singleSignOnService": {
            "url": "https://idp.example.com/sso",
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "singleLogoutService": {
            "url": "https://idp.example.com/slo", 
            "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        },
        "x509cert": "single_cert_string",
        # OR for multiple certificates:
        "x509certMulti": {
            "signing": ["cert1", "cert2"],
            "encryption": ["cert3", "cert4"]
        }
    },
    "security": {
        "authnRequestsSigned": True
    },
    "sp": {
        "NameIDFormat": "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"
    }
}

Usage Patterns

Settings Configuration from Files

# Load from settings.json and advanced_settings.json
settings = OneLogin_Saml2_Settings(custom_base_path="/path/to/config")

# Load from dictionary
settings_dict = {
    "sp": {...},
    "idp": {...},
    "security": {...}
}
settings = OneLogin_Saml2_Settings(settings_dict)

# Validate configuration
errors = settings.check_settings(settings_dict)
if errors:
    print(f"Configuration errors: {errors}")

Metadata Generation

from onelogin.saml2.metadata import OneLogin_Saml2_Metadata
from onelogin.saml2.settings import OneLogin_Saml2_Settings

settings = OneLogin_Saml2_Settings(config_dict)
sp_data = settings.get_sp_data()

# Generate basic metadata
metadata_xml = OneLogin_Saml2_Metadata.builder(sp_data)

# Generate signed metadata with organizational info
contacts = {
    "technical": {
        "givenName": "Tech Team",
        "emailAddress": "tech@example.com"
    }
}

organization = {
    "en-US": {
        "name": "My Organization",
        "displayname": "My Org",
        "url": "https://myorg.com"
    }
}

signed_metadata = OneLogin_Saml2_Metadata.builder(
    sp_data,
    authnsign=True,
    wsign=True,
    contacts=contacts,
    organization=organization
)

# Sign the metadata
sp_key = settings.get_sp_key()
sp_cert = settings.get_sp_cert()
final_metadata = OneLogin_Saml2_Metadata.sign_metadata(
    signed_metadata, sp_key, sp_cert
)

IdP Metadata Integration

from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser

# Parse remote IdP metadata
idp_settings = OneLogin_Saml2_IdPMetadataParser.parse_remote(
    "https://idp.example.com/metadata",
    entity_id="https://specific.idp.entity.id"
)

# Merge with existing SP settings
complete_settings = {
    "sp": sp_configuration,
    **idp_settings
}

# Initialize settings with parsed IdP data
settings = OneLogin_Saml2_Settings(complete_settings)

Certificate Management

# Get certificates for validation
sp_cert = settings.get_sp_cert()
sp_key = settings.get_sp_key()
idp_cert = settings.get_idp_cert()

# Validate certificate availability
cert_valid = settings.check_sp_certs()

# Access security configuration
security_config = settings.get_security_data()
print(f"Require signed assertions: {security_config.get('wantAssertionsSigned')}")

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