Mastering the Implementation of SAML 2.0 Authentication in Django

Varun Sharma
4 min readJul 1, 2023
Photo by Nick Fewings on Unsplash

Want to boost the security and enrich the user experience of your Django web application? Integrating SAML 2.0 (Security Assertion Markup Language) authentication could be your ticket. If you haven’t already, I recommend reading the article where I have shared the problems related to this architecture and SAML, which you can find here. This article will guide you step-by-step through the process of implementing SAML 2.0 authentication in your Django app, facilitating users to authenticate effortlessly through an Identity Provider (IdP) and access your application.

Prerequisites: Before we take the plunge, ensure that you possess a foundational understanding of Django and web development concepts. Having a grasp of SAML 2.0 and Single Sign-On (SSO) principles will be advantageous in following this guide.

Step 1: Installing Dependencies: Our journey begins by installing the required dependencies. Fire up your terminal and execute the following command:

pip install python3-saml

Make sure your Django project is up and running before you proceed further.

Step 2: Configuring SAML Settings: Next, we’ll create a saml_settings.py file within your Django project. This file will house your SAML specific configuration settings. You’re free to choose an appropriate location for this file. Here’s a peek at the structure of the saml_settings.py file:

SAML_SETTINGS = {
'strict': True,
'debug': False,
'sp': {
'entityId': 'https://your-app.com/metadata',
'assertionConsumerService': {
'url': 'https://your-app.com/saml/callback',
'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
},
'singleLogoutService': {
'url': 'https://your-app.com/saml/logout',
'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
},
'NameIDFormat': 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified',
'x509cert': '',
'privateKey': '',
},
'idp': {
'entityId': 'https://idp-provider.com/metadata',
'singleSignOnService': {
'url': 'https://idp-provider.com/sso',
'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
},
'singleLogoutService': {
'url': 'https://idp-provider.com/slo',
'binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
},
'x509cert': '',
},
}

Substitute the placeholders with the actual values matching your SAML configuration. These settings elucidate the details of communication with the IdP, including the Entity ID, Single Sign-On (SSO) URL, Single Logout (SLO) URL, Assertion Consumer Service (ACS) URL, and other necessary certificates and keys.

Step 3: Crafting the SAML Login View: To kickstart the SAML authentication process, we’ll fashion a Django view that redirects the user to the IdP’s login page. Here’s a sample implementation:

from django.shortcuts import redirect
from django.views import View
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from saml_settings import SAML_SETTINGS

class SAMLLoginView(View):
def get(self, request):
auth = OneLogin_Saml2_Auth(request, SAML_SETTINGS)
return redirect(auth.login())

In this view, we initialize the OneLogin_Saml2_Auth class with the supplied SAML_SETTINGS and then redirect the user to the IdP’s login page using the login() method, allowing the user to authenticate via the IdP.

Step 4: Managing the SAML Response in a Callback View: Once the user authenticates with the IdP, a SAML response is returned to your Django application. We need to create a view to manage this response. Here’s a model implementation:

from django.http import HttpResponseBadRequest, JsonResponse
from django.views import View
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from saml_settings import SAML_SETTINGS

class SAMLCallbackView(View):
def post(self, request):
auth = OneLogin_Saml2_Auth(request, SAML_SETTINGS)
auth.process_response()
if not auth.is_authenticated():
return HttpResponseBadRequest("SAML authentication failed.")
# Extract user attributes for authentication and authorization
attributes = auth.get_attributes()
username = attributes.get('username')[0]
email = attributes.get('email')[0]
# Add more attribute extraction as per your requirements
# Implement your authentication and authorization logic here
# For example, create a new user or authenticate an existing user based on the SAML attributes
# Once authenticated, generate a JWT token
jwt_token = generate_jwt_token(username, email) # Replace with your JWT token generation logic
# Return the JWT token to the client
return JsonResponse({'token': jwt_token})

In this view, we leverage the OneLogin_Saml2_Auth class to process the SAML response received from the IdP. We validate the response and verify if the user is authenticated. If the authentication is successful, we extract the necessary user attributes with the get_attributes() method. Customize this section to pull out the attributes significant for your application.

After authenticating the user, you can deploy your own authentication and authorization logic based on the extracted user attributes. For instance, you could create a new user or authenticate an existing user grounded on the SAML attributes. Lastly, generate a JWT token using your favored method and return it to the client for subsequent authentication and authorization.

Bravo! You’ve accomplished implementing SAML 2.0 authentication in your Django web application. Through SAML integration, you’ve amplified the security and user experience by facilitating seamless authentication via an Identity Provider. This reduces the dependency on separate login credentials and simplifies user management.

Don’t forget to tailor the SAML settings to your specific IdP and application requirements. Additionally, modify the attribute extraction and authentication logic to align with your application’s user management system and business regulations.

Implementing SAML 2.0 authentication in Django equips you with a secure and streamlined login process, bolstering both usability and security. Savor the perks of Single Sign-On and elevate your Django application experience to new heights!

Implementing SAML 2.0 authentication in Django equips you with a secure and streamlined login process, bolstering both usability and security. Savor the perks of Single Sign-On and elevate your Django application experience to new heights!

--

--

Varun Sharma

Fall in love with building products, now learning to make them successful.