Registry / auth-security / pysaml2

pysaml2

JSON →
library7.5.4pypypi✓ verified 26d ago

PySAML2 is a pure Python implementation of the SAML Version 2 Standard. It provides a comprehensive toolkit for building both Service Providers (SP) and Identity Providers (IdP), handling SAML assertions, requests, and responses. The library is designed to work within WSGI environments but can also be utilized in non-WSGI contexts. The current version, 7.5.4, demonstrates active development with recent releases and ongoing maintenance.

pip install pysaml2
INSTALL
IMPORT
SIG · PYSAML2
P
pysaml2
auth-securitypythonv7.5.4
Install
4.1s avg
Import
5015ms
Disk
45MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v7.5.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 5.060s · 45.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 4.1s · import 4.970s · 46MB
45MB installed
● package 45MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Config
from saml2.config import Config
Saml2Client
from saml2.client import Saml2Client
BINDING_HTTP_REDIRECT
from saml2 import BINDING_HTTP_REDIRECT

This quickstart demonstrates the basic initialization of a PySAML2 Service Provider (SP) client. It sets up a minimal configuration using `saml2.config.Config` and creates a `saml2.client.Saml2Client` instance. For a functional SAML flow, you would need real IdP metadata, proper key/certificate files, and a web server to handle redirects and POST requests. Remember that `xmlsec1` must be installed on your system for signature and encryption operations.

import os from saml2.config import Config from saml2.client import Saml2Client from saml2 import BINDING_HTTP_REDIRECT # Minimal configuration for a Service Provider (SP) # In a real application, this would be loaded from a file or more extensive setup. SP_CONFIG = { "entityid": "http://localhost:8080/saml2/metadata", "service": { "sp": { "endpoints": { "assertion_consumer_service": [ ("http://localhost:8080/saml2/acs", BINDING_HTTP_REDIRECT), ], "single_logout_service": [ ("http://localhost:8080/saml2/slo", BINDING_HTTP_REDIRECT), ], }, "idp": { # Example IdP metadata URL - replace with your actual IdP's metadata "http://idp.example.com/metadata": None }, "key_file": os.environ.get("SAML_SP_KEY_FILE", "pki/mykey.pem"), "cert_file": os.environ.get("SAML_SP_CERT_FILE", "pki/mycert.pem"), } }, "metadata": [ { "class": "saml2.mdstore.MetaDataFile", "metadata": [(os.environ.get("SAML_IDP_METADATA_FILE", "idp.xml"),)] }, ], "debug": True, } def initialize_saml_client(): sp_config = Config() sp_config.load(SP_CONFIG, metadata_reload=False) client = Saml2Client(config=sp_config) print("SAML2 Client initialized successfully.") print(f"SP Entity ID: {client.config.entityid}") # In a real app, you would now use 'client' to handle SAML flows # e.g., create_authn_request, parse_response, etc. if __name__ == "__main__": # Ensure dummy cert/key files exist for basic execution if not provided via env vars os.makedirs("pki", exist_ok=True) if not os.path.exists("pki/mykey.pem"): with open("pki/mykey.pem", "w") as f: f.write("# Dummy private key content\n") if not os.path.exists("pki/mycert.pem"): with open("pki/mycert.pem", "w") as f: f.write("# Dummy public certificate content\n") if not os.path.exists("idp.xml"): with open("idp.xml", "w") as f: f.write("<EntityDescriptor entityID='http://idp.example.com/metadata'/>") initialize_saml_client()
Debug
Known issues
breakingPySAML2 v7.0.0 introduced a breaking change by replacing the default encryption method `rsa-1_5` with `rsa-oaep-mgf1p` for improved security. This may require updating configurations or interoperability testing with existing Identity Providers.
fix
Review your SAML configurations for encryption algorithms. If interoperability issues arise, ensure both SP and IdP support `rsa-oaep-mgf1p` or adjust configuration if an alternative is necessary and supported.
affects: >=7.0.0
gotchaPySAML2 relies on the external `xmlsec1` binary for critical cryptographic operations like signature validation and XML encryption/decryption. This binary must be installed at the system level.
fix
Install `xmlsec1` on your operating system (e.g., `sudo apt-get install xmlsec1` on Debian/Ubuntu, `sudo yum install xmlsec1-openssl` on RHEL/CentOS/Fedora, `brew install xmlsec1` on macOS).
affects: All versions
gotchaPySAML2 has transitioned to Python 3 only. Python 2 compatibility has been dropped, and using it with Python 2 will result in errors.
fix
Ensure your project runs on Python 3.9 or newer, as specified by the library's `requires_python` metadata.
affects: Versions released after Python 2 end-of-life (effectively ~v4.x onwards, definitively v7.x)
gotchaThe configuration of PySAML2 entities (SP/IdP) is critical and often complex, typically involving a Python module that defines a `CONFIG` dictionary. Misconfigurations are a common source of errors.
fix
Refer to the official PySAML2 documentation's 'Configuration of PySAML2 entities' section. Utilize the provided example configuration files as a starting point and adapt them carefully, paying close attention to entity IDs, endpoints, certificates, and metadata.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'saml2'
Developers often install the `pysaml2` library but mistakenly try to import `pysaml2` instead of the actual package name, which is `saml2`.
fix
Use `import saml2` or `from saml2 import ...` in your Python code after installing the library with `pip install pysaml2`.
saml2.s_exceptions.XMLSecurityError: Could not verify signature
This error indicates that the SAML message's digital signature could not be validated, often due to an incorrect xmlsec1 setup, a missing or invalid signing certificate/public key, or a tampered assertion.
fix
Ensure `xmlsec1` is correctly installed and accessible on your system, verify that the IdP's signing certificate (public key) is correctly configured in your `pysaml2` settings or metadata, and check the integrity of the SAML message.
saml2.saml.AudienceRestrictionError: Audience restriction not met
The SAML assertion received from the Identity Provider specifies an audience that does not match any of the configured entity IDs or valid audience URIs for the Service Provider in your `pysaml2` configuration.
fix
Adjust your `pysaml2` SP configuration (e.g., `config['entityid']` or `config['service']['sp']['required_attributes']['audience']`) to precisely match the audience URI expected by the IdP, or configure the IdP to send the correct audience for your SP.
saml2.s_utils.MetaDataFileError
This error occurs when `pysaml2` cannot find or properly parse the SAML metadata file (e.g., for the IdP or SP) specified in the configuration, often due to an incorrect path or malformed XML content.
fix
Verify that the absolute path to the metadata file in your `pysaml2` configuration is correct, and ensure the file exists and contains valid, well-formed XML conforming to the SAML 2.0 metadata schema.
Upgrade
Version history
7.5.4latest on PyPI · released Oct 7, 2025
Audit
Dependencies
xmlsec1requiredRequired for SAML signature validation and encryption operations. This is a system-level binary dependency.
Agent activity
12 hits · last 30 days
node
10
OpenAI (training)
1
Resources
pysaml2 — pip install pysaml2 · libregistry