django-azure-auth


Namedjango-azure-auth JSON
Version 1.3.0 PyPI version JSON
download
home_pagehttps://github.com/Weird-Sheep-Labs/django-azure-auth
SummaryA simple Django app for user authentication with Azure Active Directory/Entra ID.
upload_time2024-04-27 16:50:30
maintainerNone
docs_urlNone
authorWeird Sheep Labs
requires_python<4.0,>=3.8
licenseMIT
keywords django azure authentication microsoft entra
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![Build](https://github.com/Weird-Sheep-Labs/django-azure-auth/actions/workflows/ci.yml/badge.svg)
![Coverage Status](./reports/coverage/coverage-badge.svg?dummy=8484744)

# django-azure-auth

### A simple Django app for user authentication with Azure Active Directory/Entra ID.

by [Weird Sheep Labs](https://weirdsheeplabs.com)

<a target="_blank" href="https://weirdsheeplabs.com"><img src="https://weirdsheeplabs.com/android-chrome-192x192.png" height="40" width="40" /></a>

#### Naming update

In March 2024, [Microsoft renamed Azure Active Directory (Azure AD) to Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/fundamentals/new-name).

## Description

`django-azure-auth` is a Django app which wraps the great [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-python)
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:

```bash
pip install django-azure-auth
```

## Configuration

### Azure setup

- Register an app at https://portal.azure.com/.
- Add a client secret and note it down.
- Add a redirect URI of the format `https://<domain>/azure_auth/callback`.

### Settings

Add the following to your `settings.py`, replacing the variables in braces with the values
from your Azure app:

```python
AZURE_AUTH = {
    "CLIENT_ID": "<client id>",
    "CLIENT_SECRET": "<client secret>",
    "REDIRECT_URI": "https://<domain>/azure_auth/callback",
    "SCOPES": ["User.Read"],
    "AUTHORITY": "https://login.microsoftonline.com/<tenant id>",   # Or https://login.microsoftonline.com/common if multi-tenant
    "LOGOUT_URI": "https://<domain>/logout",    # Optional
    "PUBLIC_URLS": ["<public:view_name>",],  # Optional, public views accessible by non-authenticated users
    "PUBLIC_PATHS": ['/go/',],  # Optional, public paths accessible by non-authenticated users
    "ROLES": {
        "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1",
        "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2"
    }  # Optional, will add user to django group if user is in EntraID group
}
LOGIN_URL = "/azure_auth/login"
LOGIN_REDIRECT_URL = "/"    # Or any other endpoint
```

#### Note: You should obfuscate the credentials by using environment variables.

### Installed apps

Add the following to your `INSTALLED_APPS`:

```python
INSTALLED_APPS = (
    "...",
    "azure_auth",
    "..."
)
```

### Authentication backend

Configure the authentication backend:

```python
AUTHENTICATION_BACKENDS = ("azure_auth.backends.AzureBackend",)
```

### URLs

Include the app's URLs in your `urlpatterns`:

```python
from django.urls import path, include

urlpatterns = [
    path("azure_auth/", include("azure_auth.urls"),),
]
```

## Usage

### Decorator

To make user authentication a requirement for accessing an individual view, decorate the
view like so:

```python
from azure_auth.decorators import azure_auth_required
from django.shortcuts import HttpResponse

@azure_auth_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`:

```python
MIDDLEWARE = [
    "...",
    "azure_auth.middleware.AzureMiddleware",
    "...",
]
```

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_AUTH["PUBLIC_URLS"]`, as
shown above.

## Groups Management

Adding a group to the Azure Enterprise application will pass the group id down to the application via the token.
This happens only, if the user is part of the group. In this case the group will be listed in the `token`.

On how to configure this in Azure see here: https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-fed-group-claims

Groups available in the token are synced with the corresponding django groups. Therfor the group id's from Azure need to be mapped in the
settings with the Django groups by adding the following to `AZURE_AUTH` in `settings`.

```
"ROLES": {
        "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1",
        "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2"
    }
```

If a user is assigned to one or more of this groups listed in the configuration, the user will be added
automatically to the respective Django group. The group will be created if it does not exist.
If a user is not part of a group (revoke permissions case), but is still in the Django group, the user
will be removed from the Django group.

## Bypass logout account selection

During logout, if the ID token includes only the default claims, Active Directory will present the user with a page prompting them to select the account to log out. To disable this, simply enable the `login_hint` optional claim in your client application in Azure, as described in https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc#send-a-sign-out-request.

## Credits

This app is heavily inspired by and builds on functionality in
https://github.com/shubhamdipt/django-microsoft-authentication, with both feature
improvements and code assurance through testing.

Credit also to:

- https://github.com/Azure-Samples/ms-identity-python-webapp
- https://github.com/AzMoo/django-okta-auth

<div align="center">
    <a target="_blank" href="https://weirdsheeplabs.com"><img src="https://weirdsheeplabs.com/android-chrome-192x192.png" height="50" width="50" /></a>
</div>

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Weird-Sheep-Labs/django-azure-auth",
    "name": "django-azure-auth",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": "django, azure, authentication, microsoft, entra",
    "author": "Weird Sheep Labs",
    "author_email": "info@weirdsheeplabs.com",
    "download_url": "https://files.pythonhosted.org/packages/5f/22/31e58fc0e991b25afee6dc78f1d6481546e074fdb90b517b776730cdd78d/django_azure_auth-1.3.0.tar.gz",
    "platform": null,
    "description": "![Build](https://github.com/Weird-Sheep-Labs/django-azure-auth/actions/workflows/ci.yml/badge.svg)\n![Coverage Status](./reports/coverage/coverage-badge.svg?dummy=8484744)\n\n# django-azure-auth\n\n### A simple Django app for user authentication with Azure Active Directory/Entra ID.\n\nby [Weird Sheep Labs](https://weirdsheeplabs.com)\n\n<a target=\"_blank\" href=\"https://weirdsheeplabs.com\"><img src=\"https://weirdsheeplabs.com/android-chrome-192x192.png\" height=\"40\" width=\"40\" /></a>\n\n#### Naming update\n\nIn March 2024, [Microsoft renamed Azure Active Directory (Azure AD) to Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/fundamentals/new-name).\n\n## Description\n\n`django-azure-auth` is a Django app which wraps the great [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-python)\npackage to enable authentication against Microsoft's Azure Active Directory in Django projects.\n\nThe app includes `login`, `logout` and `callback` authentication views, a decorator\nto protect individual views, and middleware which allows the entire site to require user\nauthentication by default, with the ability to exempt specified views.\n\nThis project is in no way affiliated with Microsoft.\n\n## Installation\n\nFrom PyPi:\n\n```bash\npip install django-azure-auth\n```\n\n## Configuration\n\n### Azure setup\n\n- Register an app at https://portal.azure.com/.\n- Add a client secret and note it down.\n- Add a redirect URI of the format `https://<domain>/azure_auth/callback`.\n\n### Settings\n\nAdd the following to your `settings.py`, replacing the variables in braces with the values\nfrom your Azure app:\n\n```python\nAZURE_AUTH = {\n    \"CLIENT_ID\": \"<client id>\",\n    \"CLIENT_SECRET\": \"<client secret>\",\n    \"REDIRECT_URI\": \"https://<domain>/azure_auth/callback\",\n    \"SCOPES\": [\"User.Read\"],\n    \"AUTHORITY\": \"https://login.microsoftonline.com/<tenant id>\",   # Or https://login.microsoftonline.com/common if multi-tenant\n    \"LOGOUT_URI\": \"https://<domain>/logout\",    # Optional\n    \"PUBLIC_URLS\": [\"<public:view_name>\",],  # Optional, public views accessible by non-authenticated users\n    \"PUBLIC_PATHS\": ['/go/',],  # Optional, public paths accessible by non-authenticated users\n    \"ROLES\": {\n        \"95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7\": \"GroupName1\",\n        \"3dc6539e-0589-4663-b782-fef100d839aa\": \"GroupName2\"\n    }  # Optional, will add user to django group if user is in EntraID group\n}\nLOGIN_URL = \"/azure_auth/login\"\nLOGIN_REDIRECT_URL = \"/\"    # Or any other endpoint\n```\n\n#### Note: You should obfuscate the credentials by using environment variables.\n\n### Installed apps\n\nAdd the following to your `INSTALLED_APPS`:\n\n```python\nINSTALLED_APPS = (\n    \"...\",\n    \"azure_auth\",\n    \"...\"\n)\n```\n\n### Authentication backend\n\nConfigure the authentication backend:\n\n```python\nAUTHENTICATION_BACKENDS = (\"azure_auth.backends.AzureBackend\",)\n```\n\n### URLs\n\nInclude the app's URLs in your `urlpatterns`:\n\n```python\nfrom django.urls import path, include\n\nurlpatterns = [\n    path(\"azure_auth/\", include(\"azure_auth.urls\"),),\n]\n```\n\n## Usage\n\n### Decorator\n\nTo make user authentication a requirement for accessing an individual view, decorate the\nview like so:\n\n```python\nfrom azure_auth.decorators import azure_auth_required\nfrom django.shortcuts import HttpResponse\n\n@azure_auth_required\ndef protected_view(request):\n    return HttpResponse(\"A view protected by the decorator\")\n```\n\n### Middleware\n\nIf you want to protect your entire site by default, you can use the middleware by adding the\nfollowing to your `settings.py`:\n\n```python\nMIDDLEWARE = [\n    \"...\",\n    \"azure_auth.middleware.AzureMiddleware\",\n    \"...\",\n]\n```\n\nMake sure you add the middleware after Django's `session` and `authentication` middlewares so\nthat the request includes the session and user objects. Public URLs which need to be accessed by\nnon-authenticated users should be specified in the `settings.AZURE_AUTH[\"PUBLIC_URLS\"]`, as\nshown above.\n\n## Groups Management\n\nAdding a group to the Azure Enterprise application will pass the group id down to the application via the token.\nThis happens only, if the user is part of the group. In this case the group will be listed in the `token`.\n\nOn how to configure this in Azure see here: https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/how-to-connect-fed-group-claims\n\nGroups available in the token are synced with the corresponding django groups. Therfor the group id's from Azure need to be mapped in the\nsettings with the Django groups by adding the following to `AZURE_AUTH` in `settings`.\n\n```\n\"ROLES\": {\n        \"95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7\": \"GroupName1\",\n        \"3dc6539e-0589-4663-b782-fef100d839aa\": \"GroupName2\"\n    }\n```\n\nIf a user is assigned to one or more of this groups listed in the configuration, the user will be added\nautomatically to the respective Django group. The group will be created if it does not exist.\nIf a user is not part of a group (revoke permissions case), but is still in the Django group, the user\nwill be removed from the Django group.\n\n## Bypass logout account selection\n\nDuring logout, if the ID token includes only the default claims, Active Directory will present the user with a page prompting them to select the account to log out. To disable this, simply enable the `login_hint` optional claim in your client application in Azure, as described in https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc#send-a-sign-out-request.\n\n## Credits\n\nThis app is heavily inspired by and builds on functionality in\nhttps://github.com/shubhamdipt/django-microsoft-authentication, with both feature\nimprovements and code assurance through testing.\n\nCredit also to:\n\n- https://github.com/Azure-Samples/ms-identity-python-webapp\n- https://github.com/AzMoo/django-okta-auth\n\n<div align=\"center\">\n    <a target=\"_blank\" href=\"https://weirdsheeplabs.com\"><img src=\"https://weirdsheeplabs.com/android-chrome-192x192.png\" height=\"50\" width=\"50\" /></a>\n</div>\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A simple Django app for user authentication with Azure Active Directory/Entra ID.",
    "version": "1.3.0",
    "project_urls": {
        "Homepage": "https://github.com/Weird-Sheep-Labs/django-azure-auth"
    },
    "split_keywords": [
        "django",
        " azure",
        " authentication",
        " microsoft",
        " entra"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8d49a70f16010cd05fdc6d37f52ad1db017021eb3cb1edaaa8ac9c310b7a2774",
                "md5": "31bfc8ef711a2c7e9c1f2752f5c990ea",
                "sha256": "c6fff436757c834d73c04d5a15a2918a21dcfb892c862b1cea283b682bb7efc0"
            },
            "downloads": -1,
            "filename": "django_azure_auth-1.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "31bfc8ef711a2c7e9c1f2752f5c990ea",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 17036,
            "upload_time": "2024-04-27T16:50:29",
            "upload_time_iso_8601": "2024-04-27T16:50:29.574300Z",
            "url": "https://files.pythonhosted.org/packages/8d/49/a70f16010cd05fdc6d37f52ad1db017021eb3cb1edaaa8ac9c310b7a2774/django_azure_auth-1.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5f2231e58fc0e991b25afee6dc78f1d6481546e074fdb90b517b776730cdd78d",
                "md5": "57737caa253a7049a178e2dfe6d45d3a",
                "sha256": "0bda7880e7ecdc01092ea65223ba4b58b4485e0ea57fa0e4a932c209fe152b50"
            },
            "downloads": -1,
            "filename": "django_azure_auth-1.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "57737caa253a7049a178e2dfe6d45d3a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 14333,
            "upload_time": "2024-04-27T16:50:30",
            "upload_time_iso_8601": "2024-04-27T16:50:30.640663Z",
            "url": "https://files.pythonhosted.org/packages/5f/22/31e58fc0e991b25afee6dc78f1d6481546e074fdb90b517b776730cdd78d/django_azure_auth-1.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-27 16:50:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Weird-Sheep-Labs",
    "github_project": "django-azure-auth",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-azure-auth"
}
        
Elapsed time: 0.24051s