Sign-in users to your Django Web app with Azure Active Directory.
Project description
Django Azure Active Directory Sign-In
Sign-in users to your Django Web app with Azure Active Directory.
Description
django-azure-active-directory-signin
is a Django app which wraps the great MSAL
package to enable authentication against Microsoft's Azure Active Directory in Django projects.
The app includes login
, logout
and callback
authentication views, a decorator
to protect individual views, and middleware which allows the entire site to require user
authentication by default, with the ability to exempt specified views.
This project is in no way affiliated with Microsoft.
Installation
From PyPi:
pip install django-azure-active-directory-signin
Configuration
Azure App Registration setup
- Register an app at https://portal.azure.com/.
- Add a client secret and note it down.
- Complete the Redirect URI list:
https://<your-domain>/azure-signin/callback
https://127.0.0.1:8000/azure-signin/callback
https://localhost:8000/azure-signin/callback
Settings
Add the following to your settings.py
, replacing the variables in braces with the values
from your Azure app:
INSTALLED_APPS += [
"azure_signin",
]
AZURE_SIGNIN = {
"CLIENT_ID": os.environ.get("CLIENT_ID"),
"CLIENT_SECRET": os.environ.get("CLIENT_SECRET"),
"TENANT_ID": os.environ.get("TENANT_ID"),
"RENAME_ATTRIBUTES": [
("employeeNumber", "employee_id"),
("affiliationNumber", "omk2"),
],
"REDIRECT_URI": "https://<domain>/azure_signin/callback", # Optional
"SCOPES": ["User.Read.All"], # Optional
"AUTHORITY": "https://login.microsoftonline.com/<tenant id>", # Optional Or https://login.microsoftonline.com/common if multi-tenant
"LOGOUT_REDIRECT_URI": "https://<domain>/logout", # Optional
"PUBLIC_URLS": ["<public:view_name>",] # Optional, public views accessible by non-authenticated users
}
AUTHENTICATION_BACKENDS += [
"azure_signin.backends.AzureSigninBackend",
]
LOGIN_URL = "azure_signin:login"
LOGIN_REDIRECT_URL = "/" # Or any other endpoint
LOGOUT_REDIRECT_URL = LOGIN_REDIRECT_URL
Note: You should obfuscate the credentials by using environment variables
Installed apps
Add the following to your INSTALLED_APPS
:
INSTALLED_APPS += [
"azure_signin",
]
Authentication backend
Configure the authentication backend:
AUTHENTICATION_BACKENDS += [
"azure_signin.backends.AzureSigninBackend",
]
Can be subclassed to cutomize validation rules for users.
import logging
from azure_signin.backends import AzureSigninBackend
logger = logging.getLogger(__name__)
class CustomAzureSigninBackend(AzureSigninBackend):
"Subclass AzureSigninBackend to cutomize validation rules for users."
def is_valid_user(self, user: dict, *args, **kwargs) -> bool:
"is_valid_user"
output = super().is_valid_user(user, *args, **kwargs):
try:
"run extra tests here..."
pass
except Exception as e:
logger.exception(e)
logger.debug("is_valid_user: %s", output)
return output
URLs
Include the app's URLs in your urlpatterns
:
from django.urls import path, include
urlpatterns += [
path("azure-signin/", include("azure_signin.urls", namespace="azure_signin")),
]
Usage
Decorator
To make user authentication a requirement for accessing an individual view, decorate the view like so:
from azure_signin.decorators import azure_signin_required
from django.shortcuts import HttpResponse
@azure_signin_required
def protected_view(request):
return HttpResponse("A view protected by the decorator")
Middleware
If you want to protect your entire site by default, you can use the middleware by adding the
following to your settings.py
:
MIDDLEWARE += [
"azure_signin.middleware.AzureSigninMiddleware",
]
Make sure you add the middleware after Django's session
and authentication
middlewares so
that the request includes the session and user objects. Public URLs which need to be accessed by
non-authenticated users should be specified in the settings.AZURE_SIGNIN["PUBLIC_URLS"]
, as
shown above.
Credits
This app is heavily inspired by and builds on functionality in https://github.com/AgileTek/django-azure-auth, with both feature improvements and code assurance through testing.
Readings 📚
- Quickstart: Add sign-in with Microsoft to a web app (docs.microsoft.com)
- Microsoft Graph REST API v1.0 Permissions (from least to most privileged):
User.Read, User.ReadWrite, User.ReadBasic.All, User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All
(docs.microsoft.com)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django-azure-active-directory-signin-0.1.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | cad8a8974ff004f1b2fa8d4608a1e7d2998f844a06cb690a4c49e680ddf34205 |
|
MD5 | 53c4d8a8c0842939c017a5b052cf6fcf |
|
BLAKE2b-256 | 67822228286bff966555b047c9c902409e7828298fa370dcadcb3cfa28f828ce |
Hashes for django_azure_active_directory_signin-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 59654b1a33a3443618c47117ccf08263dc3ac7636de4c58d640f89ad1fecb354 |
|
MD5 | 7a618ac299ac6b48f5cf65a4c9e0560d |
|
BLAKE2b-256 | 48085c14064ef14d783478ce14f35aea018a7096bef68bc83567721df11bcaa7 |