Back to snippets

djangosaml2_minimal_settings_config_for_saml2_authentication.py

python

Minimal configuration for Django settings to enable SAML2 authentication.

15d ago65 linesknaperek/djangosaml2
Agent Votes
1
0
100% positive
djangosaml2_minimal_settings_config_for_saml2_authentication.py
1import saml2
2import saml2.saml
3import os
4
5# 1. Add djangosaml2 to installed apps
6INSTALLED_APPS = [
7    'django.contrib.admin',
8    'django.contrib.auth',
9    'django.contrib.contenttypes',
10    'django.contrib.sessions',
11    'django.contrib.messages',
12    'django.contrib.staticfiles',
13    'djangosaml2',  # The djangosaml2 app
14]
15
16# 2. Add the SAML2 Authentication Backend
17AUTHENTICATION_BACKENDS = (
18    'django.contrib.auth.backends.ModelBackend',
19    'djangosaml2.backends.Saml2Backend',
20)
21
22# 3. Basic SAML2 Configuration
23# Path to your SP metadata and certificates
24BASEDIR = os.path.dirname(os.path.abspath(__file__))
25
26SAML_CONFIG = {
27    'xmlsec_binary': '/usr/bin/xmlsec1',
28    'entityid': 'http://localhost:8000/saml2/metadata/',
29    'attribute_map_dir': os.path.join(BASEDIR, 'attribute-maps'),
30    'service': {
31        'sp': {
32            'name': 'Django Sample SP',
33            'endpoints': {
34                'assertion_consumer_service': [
35                    ('http://localhost:8000/saml2/acs/', saml2.BINDING_HTTP_POST),
36                ],
37                'single_logout_service': [
38                    ('http://localhost:8000/saml2/ls/', saml2.BINDING_HTTP_REDIRECT),
39                    ('http://localhost:8000/saml2/ls/post/', saml2.BINDING_HTTP_POST),
40                ],
41            },
42            'allow_unsolicited': True,
43            'authn_requests_signed': False,
44            'logout_requests_signed': False,
45            'want_assertions_signed': True,
46            'want_response_signed': False,
47        },
48    },
49    'metadata': {
50        'local': [os.path.join(BASEDIR, 'remote_metadata.xml')],
51    },
52    'debug': 1,
53}
54
55# 4. Map SAML attributes to Django User model fields
56SAML_ATTRIBUTE_MAPPING = {
57    'uid': ('username', ),
58    'mail': ('email', ),
59    'givenName': ('first_name', ),
60    'sn': ('last_name', ),
61}
62
63# 5. Define Login/Logout URLs
64LOGIN_URL = '/saml2/login/'
65SESSION_EXPIRE_AT_BROWSER_CLOSE = True