Package: unicef-djangosaml2
===========djangosaml2===========.. image:: https://travis-ci.org/knaperek/djangosaml2.svg?branch=master:target: https://travis-ci.org/knaperek/djangosaml2:align: leftdjangosaml2 is a Django application that integrates the PySAML2 libraryinto your project. This mean that you can protect your Django based projectwith a service provider based on PySAML. This way it will talk SAML2 withyour Identity Provider allowing you to use this authentication mechanism.This document will guide you through a few simple steps to accomplishsuch goal... contents::Installation============PySAML2 uses xmlsec1_ binary to sign SAML assertions so you need to installit either through your operating system package or by compiling the sourcecode. It doesn't matter where the final executable is installed becauseyou will need to set the full path to it in the configuration stage... _xmlsec1: http://www.aleksey.com/xmlsec/Now you can install the djangosaml2 package using easy_install or pip. Thiswill also install PySAML2 and its dependencies automatically.Configuration=============There are three things you need to setup to make djangosaml2 work in yourDjango project:1. **settings.py** as you may already know, it is the main Djangoconfiguration file.2. **urls.py** is the file where you will include djangosaml2 urls.3. **pysaml2** specific files such as an attribute map directory and acertificate.Changes in the settings.py file-------------------------------The first thing you need to do is add ``djangosaml2`` to the list ofinstalled apps::INSTALLED_APPS = ('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.admin','djangosaml2',  # new application)Actually this is not really required since djangosaml2 does not includeany data model. The only reason we include it is to be able to rundjangosaml2 test suite from our project, something you should alwaysdo to make sure it is compatible with your Django version and environment... note::When you finish the configuration you can run the djangosaml2 test suite asyou run any other Django application test suite. Just type ``python manage.pytest djangosaml2``.Python 2 users need to ``pip install djangosaml2[test]`` in order to run thetests.Then you have to add the ``djangosaml2.backends.Saml2Backend``authentication backend to the list of authentications backends.By default only the ModelBackend included in Django is configured.A typical configuration would look like this::AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend','djangosaml2.backends.Saml2Backend',).. note::Before djangosaml2 0.5.0 this authentication backend wasautomatically added by djangosaml2. This turned out to bea bad idea since some applications want to use their owncustom policies for authorization and the authenticationbackend is a good place to define that. Starting fromdjangosaml2 0.5.0 it is now possible to define suchbackends.Finally we have to tell Django what the new login url we want to use is::LOGIN_URL = '/saml2/login/'SESSION_EXPIRE_AT_BROWSER_CLOSE = TrueHere we are telling Django that any view that requires an authenticateduser should redirect the user browser to that url if the user has notbeen authenticated before. We are also telling that when the user closeshis browser, the session should be terminated. This is useful in SAML2federations where the logout protocol is not always available... note::The login url starts with ``/saml2/`` as an example but you can change thatif you want. Check the section about changes in the ``urls.py``file for more information.If you want to allow several authentication mechanisms in your projectyou should set the LOGIN_URL option to another view and put a link in suchview to the ``/saml2/login/`` view.Preferred Logout binding------------------------Use the following setting to choose your preferred binding for SP initiated logout requests::SAML_LOGOUT_REQUEST_PREFERRED_BINDINGFor example::import saml2SAML_LOGOUT_REQUEST_PREFERRED_BINDING = saml2.BINDING_HTTP_POSTChanges in the urls.py file---------------------------The next thing you need to do is to include ``djangosaml2.urls`` module in yourmain ``urls.py`` module::urlpatterns = patterns('',#  lots of url definitions here(r'^saml2/', include('djangosaml2.urls')),#  more url definitions)As you can see we are including ``djangosaml2.urls`` under the *saml2*prefix. Feel free to use your own prefix but be consistent with whatyou have put in the ``settings.py`` file in the LOGIN_URL parameter.PySAML2 specific files and configuration----------------------------------------Once you have finished configuring your Django project you have tostart configuring PySAML. If you use just that library you have toput your configuration options in a file and initialize PySAML2 withthe path to that file.In djangosaml2 you just put the same information in the Djangosettings.py file under the SAML_CONFIG option.We will see a typical configuration for protecting a Django project::from os import pathimport saml2import saml2.samlBASEDIR = path.dirname(path.abspath(__file__))SAML_CONFIG = {# full path to the xmlsec1 binary programm'xmlsec_binary': '/usr/bin/xmlsec1',# your entity id, usually your subdomain plus the url to the metadata view'entityid': 'http://localhost:8000/saml2/metadata/',# directory with attribute mapping'attribute_map_dir': path.join(BASEDIR, 'attribute-maps'),# this block states what services we provide'service': {# we are just a lonely SP'sp' : {'name': 'Federated Django sample SP','name_id_format': saml2.saml.NAMEID_FORMAT_PERSISTENT,'endpoints': {# url and binding to the assetion consumer service view# do not change the binding or service name'assertion_consumer_service': [('http://localhost:8000/saml2/acs/',saml2.BINDING_HTTP_POST),],# url and binding to the single logout service view# do not change the binding or service name'single_logout_service': [('http://localhost:8000/saml2/ls/',saml2.BINDING_HTTP_REDIRECT),('http://localhost:8000/saml2/ls/post',saml2.BINDING_HTTP_POST),],},# attributes that this project need to identify a user'required_attributes': ['uid'],# attributes that may be useful to have but not required'optional_attributes': ['eduPersonAffiliation'],# in this section the list of IdPs we talk to are defined'idp': {# we do not need a WAYF service since there is# only an IdP defined here. This IdP should be# present in our metadata# the keys of this dictionary are entity ids'https://localhost/simplesaml/saml2/idp/metadata.php': {'single_sign_on_service': {saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SSOService.php',},'single_logout_service': {saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SingleLogoutService.php',},},},},},# where the remote metadata is stored'metadata': {'local': [path.join(BASEDIR, 'remote_metadata.xml')],},# set to 1 to output debugging information'debug': 1,# Signing'key_file': path.join(BASEDIR, 'mycert.key'),  # private part'cert_file': path.join(BASEDIR, 'mycert.pem'),  # public part# Encryption'encryption_keypairs': [{'key_file': path.join(BASEDIR, 'my_encryption_key.key'),  # private part'cert_file': path.join(BASEDIR, 'my_encryption_cert.pem'),  # public part}],# own metadata settings'contact_person': [{'given_name': 'Lorenzo','sur_name': 'Gil','company': 'Yaco Sistemas','email_address': 'lgs@yaco.es','contact_type': 'technical'},{'given_name': 'Angel','sur_name': 'Fernandez','company': 'Yaco Sistemas','email_address': 'angel@yaco.es','contact_type': 'administrative'},],# you can set multilanguage information here'organization': {'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')],'display_name': [('Yaco', 'es'), ('Yaco', 'en')],'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')],},'valid_for': 24,  # how long is our metadata valid}.. note::Please check the `PySAML2 documentation`_ for more information aboutthese and other configuration options... _`PySAML2 documentation`: http://pysaml2.readthedocs.io/en/latest/There are several external files and directories you have to create accordingto this configuration.The xmlsec1 binary was mentioned in the installation section. Here, in theconfiguration part you just need to put the full path to xmlsec1 so PySAML2can call it as it needs.The ``attribute_map_dir`` points to a directory with attribute mappings thatare used to translate user attribute names from several standards. It's usuallysafe to just copy the default PySAML2 attribute maps that you can find in the``tests/attributemaps`` directory of the source distribution.The ``metadata`` option is a dictionary where you can define several types ofmetadata for remote entities. Usually the easiest type is the ``local`` whereyou just put the name of a local XML file with the contents of the remoteentities metadata. This XML file should be in the SAML2 metadata format.The ``key_file`` and ``cert_file`` options reference the two parts of astandard x509 certificate. You need it to sign your metadata. For assertionencryption/decryption support please configure another set of ``key_file`` and``cert_file``, but as inner attributes of ``encryption_keypairs`` option... note::Check your openssl documentation to generate a test certificate but don'tforget to order a real one when you go into production.Custom and dynamic configuration loading........................................By default, djangosaml2 reads the pysaml2 configuration options from theSAML_CONFIG setting but sometimes you want to read this information fromanother place, like a file or a database. Sometimes you even want thisconfiguration to be different depending on the request.Starting from djangosaml2 0.5.0 you can define your own configurationloader which is a callable that accepts a request parameter and returnsa saml2.config.SPConfig object. In order to do so you set the followingsetting::SAML_CONFIG_LOADER = 'python.path.to.your.callable'User attributes---------------In the SAML 2.0 authentication process the Identity Provider (IdP) willsend a security assertion to the Service Provider (SP) upon a successfulauthentication. This assertion contains attributes about the user thatwas authenticated. It depends on the IdP configuration what exactattributes are sent to each SP it can talk to.When such assertion is received on the Django side it is used to find a Djangouser and create a session for it. By default djangosaml2 will do a query on theUser model with the USERNAME_FIELD_ attribute but you can change it to anyother attribute of the User model. For example, you can do this lookup usingthe 'email' attribute. In order to do so you should set the following setting::SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'email'.. _USERNAME_FIELD: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELDPlease, use an unique attribute when setting this option. Otherwisethe authentication process may fail because djangosaml2 will not knowwhich Django user it should pick.If your main attribute is something inherently case-insensitive (such asan email address), you may set::SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP = '__iexact'(This is simply appended to the main attribute name to form a Djangoquery. Your main attribute must be unique even given this lookup.)Another option is to use the SAML2 name id as the username by setting::SAML_USE_NAME_ID_AS_USERNAME = TrueYou can configure djangosaml2 to create such user if it is not already inthe Django database or maybe you don't want to allow users that are notin your database already. For this purpose there is another option youcan set in the settings.py file::SAML_CREATE_UNKNOWN_USER = TrueThis setting is True by default.ACS_DEFAULT_REDIRECT_URL = reverse_lazy('some_url_name')This setting lets you specify a URL for redirection after a successfulauthentication. Particularly useful when you only plan to useIdP initiated login and the IdP does not have a configured RelayStateparameter. The default is ``/``.The other thing you will probably want to configure is the mapping ofSAML2 user attributes to Django user attributes. By default only theUser.username attribute is mapped but you can add more attributes orchange that one. In order to do so you need to change theSAML_ATTRIBUTE_MAPPING option in your settings.py::SAML_ATTRIBUTE_MAPPING = {'uid': ('username', ),'mail': ('email', ),'cn': ('first_name', ),'sn': ('last_name', ),}where the keys of this dictionary are SAML user attributes and the valuesare Django User attributes.If you are using Django user profile objects to store extra attributesabout your user you can add those attributes to the SAML_ATTRIBUTE_MAPPINGdictionary. For each (key, value) pair, djangosaml2 will try to store theattribute in the User model if there is a matching field in that model.Otherwise it will try to do the same with your profile custom model. Formulti-valued attributes only the first value is assigned to the destination field.Alternatively, custom processing of attributes can be achieved by setting thevalue(s) in the SAML_ATTRIBUTE_MAPPING, to name(s) of method(s) defined on acustom django User object. In this case, each method is called by djangosaml2,passing the full list of attribute values extracted from the <saml:AttributeValue>elements of the <saml:Attribute>. Among other uses, this is a useful way to processmulti-valued attributes such as lists of user group names.For example:Saml assertion snippet::<saml:Attribute Name="groups" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"><saml:AttributeValue>group1</saml:AttributeValue><saml:AttributeValue>group2</saml:AttributeValue><saml:AttributeValue>group3</saml:AttributeValue></saml:Attribute>Custom User object::from django.contrib.auth.models import AbstractUserclass User(AbstractUser):def process_groups(self, groups):// process list of group names in argument 'groups'pass;settings.py::SAML_ATTRIBUTE_MAPPING = {'groups': ('process_groups', ),}Learn more about Django profile models at:https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-modelSometimes you need to use special logic to update the user objectdepending on the SAML2 attributes and the mapping described aboveis simply not enough. For these cases djangosaml2 provides a Djangosignal that you can listen to. In order to do so you can add thefollowing code to your app::from djangosaml2.signals import pre_user_savedef custom_update_user(sender=User, instance, attributes, user_modified, **kargs)...return True  # I modified the user objectYour handler will receive the user object, the list of SAML attributesand a flag telling you if the user is already modified and needto be saved after your handler is executed. If your handlermodifies the user object it should return True. Otherwise it shouldreturn False. This way djangosaml2 will know if it should savethe user object so you don't need to do it and no more calls tothe save method are issued.IdP setup=========Congratulations, you have finished configuring the SP side of the federation.Now you need to send the entity id and the metadata of this new SP to theIdP administrators so they can add it to their list of trusted services.You can get this information starting your Django development server andgoing to the http://localhost:8000/saml2/metadata url. If you have includedthe djangosaml2 urls under a different url prefix you need to correct thisurl.SimpleSAMLphp issues--------------------As of SimpleSAMLphp 1.8.2 there is a problem if you specify attributes inthe SP configuration. When the SimpleSAMLphp metadata parser converts theXML into its custom php format it puts the following option::'attributes.NameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'But it need to be replaced by this one::'AttributeNameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'Otherwise the Assertions sent from the IdP to the SP will have a wrongAttribute Name Format and pysaml2 will be confused.Furthermore if you have a AttributeLimit filter in your SimpleSAMLphpconfiguration  you will need to enable another attribute filter justbefore to make sure that the AttributeLimit does not remove the attributesfrom the authentication source. The filter you need to add is an AttributeMapfilter like this::10 => array('class' => 'core:AttributeMap', 'name2oid'),Testing=======One way to check if everything is working as expected is to enable thefollowing url::urlpatterns = patterns('',#  lots of url definitions here(r'^saml2/', include('djangosaml2.urls')),(r'^test/', 'djangosaml2.views.echo_attributes'),#  more url definitions)Now if you go to the /test/ url you will see your SAML attributes and alsoa link to do a global logout.You can also run the unit tests with the following command::python tests/run_tests.pyIf you have `tox`_ installed you can simply call tox inside the root directoryand it will run the tests in multiple versions of Python... _`tox`: http://pypi.python.org/pypi/toxFAQ===**Why can't SAML be implemented as an Django Authentication Backend?**well SAML authentication is not that simple as a set of credentials you canput on a login form and get a response back. Actually the user password isnot given to the service provider at all. This is by design. You have todelegate the task of authentication to the IdP and then get an asynchronousresponse from it.Given said that, djangosaml2 does use a Django Authentication Backend totransform the SAML assertion about the user into a Django user object.**Why not put everything in a Django middleware class and make our lifeseasier?**Yes, that was an option I did evaluate but at the end the current designwon. In my opinion putting this logic into a middleware has the advantageof making it easier to configure but has a couple of disadvantages: first,the middleware would need to check if the request path is one of theSAML endpoints for every request. Second, it would be too magical and incase of a problem, much harder to debug.**Why not call this package django-saml as many other Django applications?**Following that pattern then I should import the application withimport saml but unfortunately that module name is already used in pysaml2.Changes=======0.17.1 (2018-07-16)----------- A 403 (permission denied) is now raised if a SAMLResponse is replayed, instead of 500.- Dropped support for Python 3.3- Upgraded pysaml2 dependency to version 4.5.0Thanks to francoisfreitag, mhindery, vkurup, peppelinux0.16.11 (2017-12-25)----------- Dropped compatibility for Python < 2.7 and Django < 1.8.- Added a clean_attributes hook allowing backends to restructure attributes extracted from SAML response.- Log when fields are missing in a SAML response.- Log when attribute_mapping maps to nonexistent User fields.- Multiple compatibility fixes and other minor improvements and code cleanupsThanks to francoisfreitag, mhindery, charn, jdufresne0.16.10 (2017-10-02)-------------------- Bugfixes and internal refactorings.- Added support for custom USERNAME_FIELD on custom User models. Many thanks to francoisfreitag.0.16.9 (2017-09-19)-------------------- Bugfixes and minor improvements. Thanks to goetzk and AmbientLighter.- Added option SAML_LOGOUT_REQUEST_PREFERRED_BINDING- Added Django 1.11 to tox.0.16.4 (2017-09-11)-------------------- Added support for SHA-256 signing. Thanks to WebSpider.- Bugfixes. Thanks to justinsg and charn.- Error handling made more extensible. This will be further improved in next versions.0.16.1 (2017-07-15)-------------------- Bugfixes. Thanks to canni, AmbientLighter, cranti and logston.- request is now passed to authentication backend (introduced in Django 1.11). Thanks to terite.0.16.0 (2017-04-14)-------------------- Upgrade pysaml2 dependency to version 4.4.0 which fixes some serialization issues. Thanks to nakato for the report.- Added support for HTTP Redirect binding with signed authentication requests. Many thanks to liquidpele for this feature and other related refactorings.- The custom permission_denied.html template was removed in favor of standard PermissionDenied exception. Thanks to mhindery.0.15.0 (2016-12-18)-------------------- Python 3.5 support. Thanks to timheap.- Added support for callable user attributes. Thanks to andy-miracl and joetsoi.- Security improvement: "next" URL is now checked. thanks to flupzor.- Improved testability. Thanks to flupzor.- Other bugfixes and minor improvements. Thanks to jamaalscarlett, ws0w, jaywink and liquidpele.0.14.5 (2016-09-19)-------------------- Django 1.10 support. Thanks to inducer.- Various fixes and minor improvements. Thanks to ajsmilutin, ganiserb, inducer, grunichev, liquidpele and darbula0.14.4 (2016-03-29)-------------------- Fix compatibility issue with pysaml2-4.0.3+. Thanks to jimr and astoltz.- Fix Django 1.9 compatibility issue in templates. Thanks to nikoskal.0.14.3 (2016-03-18)-------------------- Upgraded to pysaml2-4.0.5.- Added 'ACS_DEFAULT_REDIRECT_URL' setting for default redirection after successful authentication. Thanks to ganiserb.0.14.2 (2016-03-11)-------------------- Released under the original 'djangosaml2' package name; abandoning the djangosaml2-knaperek fork.0.14.1 (2016-03-09)-------------------- Upgraded to pysaml2-4.0.4.0.14.0 (2016-01-28)-------------------- Upgrade to pysaml2-4.0.2. Thanks to kviktor- Django 1.9 support. Thanks to Jordi Gutiérrez Hermoso0.13.2 (2015-06-24)-------------------- Improved usage of standard Python logging.0.13.1 (2015-06-05)-------------------- Added support for djangosaml2 specific user model defined by SAML_USER_MODEL setting0.13.0 (2015-02-12)-------------------- Django 1.7 support. Thanks to Kamei Toshimitsu0.12.0 (2014-11-18)-------------------- Pysaml2 2.2.0 support. Thanks to Erick Tryzelaar0.11.0 (2014-06-15)-------------------- Django 1.5 custom user model support. Thanks to Jos van Velzen- Django 1.5 compatibility url template tag. Thanks to bula- Support Django 1.5 and 1.6. Thanks to David Evans and Justin Quick0.10.0 (2013-05-05)-------------------- Check that RelayState is not empty before redirecting into a loop. Thanksto Sam Bull for reporting this issue.- In the global logout process, when the session is lost, report an errormessage to the user and perform a local logout.0.9.2 (2013-04-19)------------------- Upgrade to pysaml2-0.4.3.0.9.1 (2013-01-29)------------------- Add a method to the authentication backend so it is possibleto customize the authorization based on SAML attributes.0.9.0 (2012-10-30)------------------- Add a signal for modifying the user just before saving it onthe update_user method of the authentication backend.0.8.1 (2012-10-29)------------------- Trim the SAML attributes before setting them to the Django objectsif they are too long. This fixes a crash with MySQL.0.8.0 (2012-10-25)------------------- Allow to use different attributes besides 'username' to look forexisting users.0.7.0 (2012-10-19)------------------- Add a setting to decide if the user should be redirected to thenext view or shown an authorization error when the user tries tologin twice.0.6.1 (2012-09-03)------------------- Remove Django from our dependencies- Restore support for Django 1.30.6.0 (2012-08-29)------------------- Add tox support configured to run the tests with Python 2.6 and 2.7- Fix some dependencies and sdist generation. Lorenzo Gil- Allow defining a logout redirect url in the settings. Lorenzo Gil- Add some logging calls to improve debugging. Lorenzo Gil- Add support for custom conf loading function. Sam Bull.- Make the tests more robust and easier to run when djangosaml2 isincluded in a Django project. Sam Bull.- Make sure the profile is not None before saving it. Bug reported byLeif Johansson0.5.0 (2012-05-22)------------------- Allow defining custom config loaders. They can be dynamic depending onthe request.- Do not automatically add the authentication backend. This waywe allow other people to add their own backends.- Support for additional attributes other than the ones that get mappedinto the User model. Those attributes get stored in the UserProfile model.0.4.2 (2012-03-23)------------------- Fix a crash in the idplist templatetag about using an old pysaml2 function- Added a test for the previous crash0.4.1 (2012-03-19)------------------- Upgrade pysaml2 dependency to version 0.4.10.4.0 (2012-03-18)------------------- Upgrade pysaml2 dependency to version 0.4.0 (update our tests as a resultof this)- Add logging calls to make debugging easier- Use the Django configured logger in pysaml20.3.3 (2012-02-14)------------------- Freeze the version of pysaml2 since we are not (yet!) compatible withversion 0.4.00.3.2 (2011-12-13)------------------- Avoid a crash when reading the SAML attribute that maps to the Djangousername0.3.1 (2011-12-01)------------------- Load the config in the render method of the idplist templatetag tomake it more flexible and reentrant.0.3.0 (2011-11-30)------------------- Templatetag to get the list of available idps.- Allow to map the same SAML attribute into several Django field.0.2.4 (2011-11-29)------------------- Fix restructured text bugs that made pypi page looks bad.0.2.3 (2011-06-14)------------------- Set a unusable password when the user is created for the first time0.2.2 (2011-06-07)------------------- Prevent infinite loop when going to the /saml2/login/ endpoint and the useris already logged in and the settings.LOGIN_REDIRECT_URL is (badly) pointingto /saml2/login.0.2.1 (2011-05-09)------------------- If no next parameter is supplied to the login view, use thesettings.LOGIN_REDIRECT_URL as default0.2.0 (2011-04-26)------------------- Python 2.4 compatible if the elementtree library is installed- Allow post processing after the authentication phase by usingDjango signals.0.1.1 (2011-04-18)------------------- Simple view to echo SAML attributes- Improve documentation- Change default behaviour when a new user is created. Now their attributesare filled this first time- Allow to set a next page after the logout0.1.0 (2011-03-16)------------------- Emancipation from the pysaml package