Registry / auth-security / python3-saml

python3-saml

JSON →
library1.16.0pypypi✓ verified 27d ago

The python3-saml library provides a robust SAML (Security Assertion Markup Language) toolkit for Python, enabling applications to act as a Service Provider (SP) for Single Sign-On (SSO) and Single Logout (SLO). It simplifies integration with various Identity Providers (IdPs). The current version is 1.16.0, and it maintains an active release cadence with updates typically every few months, focusing on security, bug fixes, and compatibility.

pip install python3-saml
INSTALL
IMPORT
SIG · PYTHON3-SAML
P
python3-saml
auth-securitypythonv1.16.0
Install
2.3s avg
Import
201ms
Disk
41MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.16.0 · 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 0.210s · 42.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.3s · import 0.192s · 43MB
41MB installed
● package 41MB
Code
Verified usage

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

OneLogin_Saml2_Auth
from onelogin.saml2.auth import OneLogin_Saml2_Auth
OneLogin_Saml2_Settings
from onelogin.saml2.settings import OneLogin_Saml2_Settings
OneLogin_Saml2_Constants
from onelogin.saml2.constants import OneLogin_Saml2_Constants

This quickstart demonstrates how to initialize the `OneLogin_Saml2_Auth` object with example settings and dummy request data. It shows how to obtain the Single Sign-On (SSO) URL for initiating an authentication flow and how to generate Service Provider (SP) metadata. For production, SAML settings must be securely loaded and contain valid certificate data and endpoint URLs for both the SP and the IdP.

import os import json from onelogin.saml2.auth import OneLogin_Saml2_Auth from onelogin.saml2.settings import OneLogin_Saml2_Settings from onelogin.saml2.constants import OneLogin_Saml2_Constants # Dummy request data, replace with actual request data from your web framework # This simulates the data typically extracted from a Flask/Django/FastAPI request object. dummy_request_data = { 'http_host': 'localhost:8000', 'script_name': '/saml/sso', 'server_port': '8000', 'get_data': {}, # GET parameters 'post_data': {}, # POST parameters 'query_string': '', 'https': 'off', # 'on' or 'off' 'requested_url': 'http://localhost:8000/saml/sso', 'metadata': {} # Used for metadata generation } # SAML settings are critical for proper functioning and security. # In a real application, load these from a secure configuration management system, # e.g., a JSON file specified by an environment variable. settings_path = os.environ.get('ONELOGIN_SAML_SETTINGS_PATH', '') settings_data = {} if settings_path and os.path.exists(settings_path): try: with open(settings_path, 'r') as f: settings_data = json.load(f) print(f"Loaded settings from {settings_path}") except Exception as e: print(f"Error loading settings from {settings_path}: {e}") else: # Minimal settings for demonstration (NOT PRODUCTION READY). # You MUST configure these with real SP and IdP details, including certificates. print("Using default minimal settings. Please provide a settings file for production.") settings_data = { 'strict': True, 'debug': True, 'sp': { 'entityId': 'http://localhost:8000/saml/metadata/', 'assertionConsumerService': { 'url': 'http://localhost:8000/saml/acs/', 'binding': OneLogin_Saml2_Constants.BINDING_HTTP_POST }, 'singleLogoutService': { 'url': 'http://localhost:8000/saml/sls/', 'binding': OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT }, 'NameIDFormat': OneLogin_Saml2_Constants.NAMEID_EMAIL_ADDRESS, 'x509cert': '', # Your SP public certificate 'privateKey': '' # Your SP private key }, 'idp': { 'entityId': 'http://idp.example.com/saml/metadata/', 'singleSignOnService': { 'url': 'http://idp.example.com/saml/sso/', 'binding': OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT }, 'singleLogoutService': { 'url': 'http://idp.example.com/saml/slo/', 'binding': OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT }, 'x509cert': '' # IdP public certificate } } try: # Initialize SAML toolkit with request data and settings auth = OneLogin_Saml2_Auth(dummy_request_data, settings_data) # Example 1: Get the SSO URL to redirect the user for login sso_url = auth.get_sso_url() print(f"\nSAML Auth initialized. SSO URL for IdP: {sso_url}") # Example 2: Get SP metadata (typically exposed at a /saml/metadata URL) settings = OneLogin_Saml2_Settings(settings_data) sp_metadata = settings.get_sp_metadata() print("\nGenerated SP Metadata (truncated to 500 chars):\n" + sp_metadata[:500] + "...") # In a real scenario, you'd handle SAML responses like this: # if 'SAMLResponse' in dummy_request_data['post_data']: # auth.process_response() # if not auth.is_authenticated(): # print(f"Authentication failed: {auth.get_errors()}") # else: # print(f"User authenticated: {auth.get_nameid()}") except Exception as e: print(f"Error during SAML initialization or operation: {e}")
Debug
Known issues
breakingThe default value for the `strict` setting changed from `False` to `True` in `v1.8.0`. This can cause unexpected validation failures for existing configurations that were implicitly relying on `strict=False`.
fix
Explicitly set `strict: False` in your SAML settings if you require less strict validation, or update your IdP metadata/SAML responses to comply with strict SAML standards.
affects: >=1.8.0
deprecatedThe `server_port` key in the request data dictionary (passed to `OneLogin_Saml2_Auth`) was deprecated in `v1.12.0`. While it might still function, reliance on it is discouraged.
fix
Ensure your request data dictionary provides accurate `http_host` and `https` values, which the library uses to determine the port implicitly or explicitly through the host string. Avoid using `server_port` directly.
affects: >=1.12.0
gotchaSAML security requires careful configuration of settings such as `rejectDeprecatedAlgorithm` (introduced in `v1.13.0`), `allowSingleLabelDomains` (introduced in `v1.10.0`), `wantAssertionsSigned`, `wantMessageSigned`, and others. Incorrectly configured settings can expose your application to vulnerabilities like Open Redirect, Reply attacks, or accepting insecure SAML messages.
fix
Always review and harden your SAML settings, especially when dealing with potentially insecure algorithms or domain configurations. Consult the official `python3-saml` security best practices and ensure all relevant `security` sub-settings are properly configured for your environment.
affects: All versions
gotchaPython 3.4 support was dropped in `v1.8.0` due to `lxml` dependency requirements. Additionally, past versions have experienced issues with `lxml` version compatibility (e.g., in `v1.14.0`, `v1.15.0`) which could lead to installation or runtime errors.
fix
Ensure you are running Python 3.5 or newer. If encountering `lxml` related issues, try updating `lxml` or checking the `python3-saml` release notes for specific `lxml` version recommendations/restrictions, or install with `pip install --no-binary :all: lxml`.
affects: >=1.8.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'onelogin'
The `python3-saml` library, when installed, exposes its functionalities under the `onelogin` package name, not `python3_saml`.
fix
Change your import statements from `from python3_saml...` to use `from onelogin.saml2.auth import OneLogin_Saml2_Auth` or `from onelogin.saml2.settings import OneLogin_Saml2_Settings`.
OneLogin_Saml2_Error: Signature validation failed.
The digital signature of the SAML response or assertion from the Identity Provider (IdP) could not be validated, typically due to an incorrect, outdated, or improperly formatted IdP public certificate in the Service Provider's (SP) settings.
fix
Ensure the `idp['x509cert']` value in your `settings` dictionary precisely matches the IdP's current public signing certificate (often found in their metadata). Also, confirm `security['wantAssertionsSigned']` and `security['wantMessagesSigned']` are correctly set.
OneLogin_Saml2_Error: Unable to find a valid SSO binding
The SAML response received from the IdP either lacks the `SAMLResponse` parameter in the expected HTTP request location (POST body or GET query string), or the binding type (HTTP-Redirect vs. HTTP-POST) doesn't match the configuration or how the response was sent.
fix
Verify that your IdP is sending the `SAMLResponse` via the correct binding (e.g., HTTP-POST) and that your application correctly extracts it from the request (e.g., `request.form.get('SAMLResponse')`). Confirm the `assertionConsumerService` URL and binding in your SP metadata match the IdP's configuration.
OneLogin_Saml2_Error: IdP entityId not found in IdP metadata
The `idp['entityId']` specified in your Service Provider (SP) settings does not precisely match any `entityID` attribute found within the Identity Provider's (IdP) metadata XML.
fix
Verify that the `entityId` in your `settings['idp']` dictionary exactly matches the `entityID` attribute from the `<EntityDescriptor>` element in your IdP's metadata XML, paying close attention to typos and case sensitivity.
Upgrade
Version history
1.16.0latest on PyPI · released Oct 9, 2023
Audit
Dependencies
lxmlrequiredXML parsing and manipulation for SAML messages.
Agent activity
8 hits · last 30 days
node
6
OpenAI (training)
1
Resources
python3-saml — pip install python3-saml · libregistry