How to Implement SAML with Python: A Step-by-Step Guide
Implementing SAML (Security Assertion Markup Language) with Python can streamline your application's authentication processes, ensuring secure and efficient single sign-on (SSO) for users. By leveraging the python3-saml library, you can easily integrate SAML into your Python application. This guide will walk you through the essential steps, including how to sign certificates and encrypt SAML responses.
Step 1: Install the Required Library
First, you need to install the python3-saml library:
sh
pip install python3-saml
Step 2: Configure Your SAML Settings
Create a settings.json file to hold your SAML configuration. This file should contain information about your Service Provider (SP) and Identity Provider (IdP).
json
{
"sp": {
"entityId": "https://your-sp.example.com/metadata/",
"assertionConsumerService": {
"url": "https://your-sp.example.com/acs/",
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
},
"singleLogoutService": {
"url": "https://your-sp.example.com/sls/",
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
"x509cert": "YOUR_SP_CERTIFICATE",
"privateKey": "YOUR_SP_PRIVATE_KEY"
},
"idp": {
"entityId": "https://idp.example.com/metadata",
"singleSignOnService": {
"url": "https://idp.example.com/SSOService.php",
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
"singleLogoutService": {
"url": "https://idp.example.com/SingleLogoutService.php",
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
},
"x509cert": "IDP_CERTIFICATE"
}
}
Step 3: Implement the SAML Authentication Flow
Use the OneLogin_Saml2_Auth class to handle SAML authentication requests and responses.
python
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from onelogin.saml2.utils import OneLogin_Saml2_Utils
import json
def init_saml_auth(req):
auth = OneLogin_Saml2_Auth(req, custom_base_path='path/to/your/saml/folder')
return auth
def prepare_flask_request(request):
url_data = urlparse(request.url)
return {
'https': 'on' if request.scheme == 'https' else 'off',
'http_host': request.host,
'server_port': url_data.port,
'script_name': request.path,
'get_data': request.args.copy(),
'post_data': request.form.copy()
}
@app.route('/sso/login')
def sso_login():
req = prepare_flask_request(request)
auth = init_saml_auth(req)
return redirect(auth.login())
@app.route('/sso/acs', methods=['POST'])
def sso_acs():
req = prepare_flask_request(request)
auth = init_saml_auth(req)
auth.process_response()
errors = auth.get_errors()
if not errors:
session['saml_user_data'] = auth.get_attributes()
return redirect('/')
return "Error: " + ", ".join(errors)
领英推荐
Step 4: Sign the Certificate and Encrypt the SAML Response
For security, ensure that your SAML assertions are signed and encrypted.
Generating the Certificates
Use OpenSSL to generate the certificates:
sh
openssl req -new -x509 -days 365 -keyout sp-private-key.pem -out sp-cert.pem
Include these certificates in your settings.json.
Signing the SAML Assertion
Configure security settings in settings.json:
json
"security": {
"authnRequestsSigned": True,
"logoutRequestSigned": True,
"logoutResponseSigned": True,
"signMetadata": True,
"wantMessagesSigned": True,
"wantAssertionsSigned": True,
"wantNameIdEncrypted": False,
"wantAssertionsEncrypted": True,
"signatureAlgorithm": "https://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"digestAlgorithm": "https://www.w3.org/2001/04/xmlenc#sha256"
}
Conclusion
By following these steps, you can successfully implement SAML in your Python application, ensuring secure and seamless authentication for your users. Signing certificates and encrypting SAML responses are crucial for maintaining the integrity and confidentiality of the authentication process.
Feel free to customize the configuration and enhance security measures based on your specific requirements. Happy coding!