README.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. ===========
  2. djangosaml2
  3. ===========
  4. .. image:: https://travis-ci.org/knaperek/djangosaml2.svg?branch=master
  5. :target: https://travis-ci.org/knaperek/djangosaml2
  6. :align: left
  7. djangosaml2 is a Django application that integrates the PySAML2 library
  8. into your project. This mean that you can protect your Django based project
  9. with a service provider based on PySAML. This way it will talk SAML2 with
  10. your Identity Provider allowing you to use this authentication mechanism.
  11. This document will guide you through a few simple steps to accomplish
  12. such goal.
  13. .. contents::
  14. Installation
  15. ============
  16. PySAML2 uses xmlsec1_ binary to sign SAML assertions so you need to install
  17. it either through your operating system package or by compiling the source
  18. code. It doesn't matter where the final executable is installed because
  19. you will need to set the full path to it in the configuration stage.
  20. .. _xmlsec1: http://www.aleksey.com/xmlsec/
  21. Now you can install the djangosaml2 package using easy_install or pip. This
  22. will also install PySAML2 and its dependencies automatically.
  23. Configuration
  24. =============
  25. There are three things you need to setup to make djangosaml2 work in your
  26. Django project:
  27. 1. **settings.py** as you may already know, it is the main Django
  28. configuration file.
  29. 2. **urls.py** is the file where you will include djangosaml2 urls.
  30. 3. **pysaml2** specific files such as an attribute map directory and a
  31. certificate.
  32. Changes in the settings.py file
  33. -------------------------------
  34. The first thing you need to do is add ``djangosaml2`` to the list of
  35. installed apps::
  36. INSTALLED_APPS = (
  37. 'django.contrib.auth',
  38. 'django.contrib.contenttypes',
  39. 'django.contrib.sessions',
  40. 'django.contrib.sites',
  41. 'django.contrib.messages',
  42. 'django.contrib.admin',
  43. 'djangosaml2', # new application
  44. )
  45. Actually this is not really required since djangosaml2 does not include
  46. any data model. The only reason we include it is to be able to run
  47. djangosaml2 test suite from our project, something you should always
  48. do to make sure it is compatible with your Django version and environment.
  49. .. note::
  50. When you finish the configuration you can run the djangosaml2 test suite as
  51. you run any other Django application test suite. Just type ``python manage.py
  52. test djangosaml2``.
  53. Python 2 users need to ``pip install djangosaml2[test]`` in order to run the
  54. tests.
  55. Then you have to add the ``djangosaml2.backends.Saml2Backend``
  56. authentication backend to the list of authentications backends.
  57. By default only the ModelBackend included in Django is configured.
  58. A typical configuration would look like this::
  59. AUTHENTICATION_BACKENDS = (
  60. 'django.contrib.auth.backends.ModelBackend',
  61. 'djangosaml2.backends.Saml2Backend',
  62. )
  63. .. note::
  64. Before djangosaml2 0.5.0 this authentication backend was
  65. automatically added by djangosaml2. This turned out to be
  66. a bad idea since some applications want to use their own
  67. custom policies for authorization and the authentication
  68. backend is a good place to define that. Starting from
  69. djangosaml2 0.5.0 it is now possible to define such
  70. backends.
  71. Finally we have to tell Django what the new login url we want to use is::
  72. LOGIN_URL = '/saml2/login/'
  73. SESSION_EXPIRE_AT_BROWSER_CLOSE = True
  74. Here we are telling Django that any view that requires an authenticated
  75. user should redirect the user browser to that url if the user has not
  76. been authenticated before. We are also telling that when the user closes
  77. his browser, the session should be terminated. This is useful in SAML2
  78. federations where the logout protocol is not always available.
  79. .. note::
  80. The login url starts with ``/saml2/`` as an example but you can change that
  81. if you want. Check the section about changes in the ``urls.py``
  82. file for more information.
  83. If you want to allow several authentication mechanisms in your project
  84. you should set the LOGIN_URL option to another view and put a link in such
  85. view to the ``/saml2/login/`` view.
  86. Preferred Logout binding
  87. ------------------------
  88. Use the following setting to choose your preferred binding for SP initiated logout requests::
  89. SAML_LOGOUT_REQUEST_PREFERRED_BINDING
  90. For example::
  91. import saml2
  92. SAML_LOGOUT_REQUEST_PREFERRED_BINDING = saml2.BINDING_HTTP_POST
  93. Changes in the urls.py file
  94. ---------------------------
  95. The next thing you need to do is to include ``djangosaml2.urls`` module in your
  96. main ``urls.py`` module::
  97. urlpatterns = patterns(
  98. '',
  99. # lots of url definitions here
  100. (r'^saml2/', include('djangosaml2.urls')),
  101. # more url definitions
  102. )
  103. As you can see we are including ``djangosaml2.urls`` under the *saml2*
  104. prefix. Feel free to use your own prefix but be consistent with what
  105. you have put in the ``settings.py`` file in the LOGIN_URL parameter.
  106. PySAML2 specific files and configuration
  107. ----------------------------------------
  108. Once you have finished configuring your Django project you have to
  109. start configuring PySAML. If you use just that library you have to
  110. put your configuration options in a file and initialize PySAML2 with
  111. the path to that file.
  112. In djangosaml2 you just put the same information in the Django
  113. settings.py file under the SAML_CONFIG option.
  114. We will see a typical configuration for protecting a Django project::
  115. from os import path
  116. import saml2
  117. import saml2.saml
  118. BASEDIR = path.dirname(path.abspath(__file__))
  119. SAML_CONFIG = {
  120. # full path to the xmlsec1 binary programm
  121. 'xmlsec_binary': '/usr/bin/xmlsec1',
  122. # your entity id, usually your subdomain plus the url to the metadata view
  123. 'entityid': 'http://localhost:8000/saml2/metadata/',
  124. # directory with attribute mapping
  125. 'attribute_map_dir': path.join(BASEDIR, 'attribute-maps'),
  126. # this block states what services we provide
  127. 'service': {
  128. # we are just a lonely SP
  129. 'sp' : {
  130. 'name': 'Federated Django sample SP',
  131. 'name_id_format': saml2.saml.NAMEID_FORMAT_PERSISTENT,
  132. 'endpoints': {
  133. # url and binding to the assetion consumer service view
  134. # do not change the binding or service name
  135. 'assertion_consumer_service': [
  136. ('http://localhost:8000/saml2/acs/',
  137. saml2.BINDING_HTTP_POST),
  138. ],
  139. # url and binding to the single logout service view
  140. # do not change the binding or service name
  141. 'single_logout_service': [
  142. ('http://localhost:8000/saml2/ls/',
  143. saml2.BINDING_HTTP_REDIRECT),
  144. ('http://localhost:8000/saml2/ls/post',
  145. saml2.BINDING_HTTP_POST),
  146. ],
  147. },
  148. # Mandates that the identity provider MUST authenticate the
  149. # presenter directly rather than rely on a previous security context.
  150. 'force_authn': False,
  151. # Enable AllowCreate in NameIDPolicy.
  152. 'name_id_format_allow_create': False,
  153. # attributes that this project need to identify a user
  154. 'required_attributes': ['uid'],
  155. # attributes that may be useful to have but not required
  156. 'optional_attributes': ['eduPersonAffiliation'],
  157. # in this section the list of IdPs we talk to are defined
  158. 'idp': {
  159. # we do not need a WAYF service since there is
  160. # only an IdP defined here. This IdP should be
  161. # present in our metadata
  162. # the keys of this dictionary are entity ids
  163. 'https://localhost/simplesaml/saml2/idp/metadata.php': {
  164. 'single_sign_on_service': {
  165. saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SSOService.php',
  166. },
  167. 'single_logout_service': {
  168. saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SingleLogoutService.php',
  169. },
  170. },
  171. },
  172. },
  173. },
  174. # where the remote metadata is stored
  175. 'metadata': {
  176. 'local': [path.join(BASEDIR, 'remote_metadata.xml')],
  177. },
  178. # set to 1 to output debugging information
  179. 'debug': 1,
  180. # Signing
  181. 'key_file': path.join(BASEDIR, 'mycert.key'), # private part
  182. 'cert_file': path.join(BASEDIR, 'mycert.pem'), # public part
  183. # Encryption
  184. 'encryption_keypairs': [{
  185. 'key_file': path.join(BASEDIR, 'my_encryption_key.key'), # private part
  186. 'cert_file': path.join(BASEDIR, 'my_encryption_cert.pem'), # public part
  187. }],
  188. # own metadata settings
  189. 'contact_person': [
  190. {'given_name': 'Lorenzo',
  191. 'sur_name': 'Gil',
  192. 'company': 'Yaco Sistemas',
  193. 'email_address': 'lgs@yaco.es',
  194. 'contact_type': 'technical'},
  195. {'given_name': 'Angel',
  196. 'sur_name': 'Fernandez',
  197. 'company': 'Yaco Sistemas',
  198. 'email_address': 'angel@yaco.es',
  199. 'contact_type': 'administrative'},
  200. ],
  201. # you can set multilanguage information here
  202. 'organization': {
  203. 'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')],
  204. 'display_name': [('Yaco', 'es'), ('Yaco', 'en')],
  205. 'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')],
  206. },
  207. 'valid_for': 24, # how long is our metadata valid
  208. }
  209. .. note::
  210. Please check the `PySAML2 documentation`_ for more information about
  211. these and other configuration options.
  212. .. _`PySAML2 documentation`: http://pysaml2.readthedocs.io/en/latest/
  213. There are several external files and directories you have to create according
  214. to this configuration.
  215. The xmlsec1 binary was mentioned in the installation section. Here, in the
  216. configuration part you just need to put the full path to xmlsec1 so PySAML2
  217. can call it as it needs.
  218. The ``attribute_map_dir`` points to a directory with attribute mappings that
  219. are used to translate user attribute names from several standards. It's usually
  220. safe to just copy the default PySAML2 attribute maps that you can find in the
  221. ``tests/attributemaps`` directory of the source distribution.
  222. The ``metadata`` option is a dictionary where you can define several types of
  223. metadata for remote entities. Usually the easiest type is the ``local`` where
  224. you just put the name of a local XML file with the contents of the remote
  225. entities metadata. This XML file should be in the SAML2 metadata format.
  226. The ``key_file`` and ``cert_file`` options reference the two parts of a
  227. standard x509 certificate. You need it to sign your metadata. For assertion
  228. encryption/decryption support please configure another set of ``key_file`` and
  229. ``cert_file``, but as inner attributes of ``encryption_keypairs`` option.
  230. .. note::
  231. Check your openssl documentation to generate a test certificate but don't
  232. forget to order a real one when you go into production.
  233. Custom and dynamic configuration loading
  234. ........................................
  235. By default, djangosaml2 reads the pysaml2 configuration options from the
  236. SAML_CONFIG setting but sometimes you want to read this information from
  237. another place, like a file or a database. Sometimes you even want this
  238. configuration to be different depending on the request.
  239. Starting from djangosaml2 0.5.0 you can define your own configuration
  240. loader which is a callable that accepts a request parameter and returns
  241. a saml2.config.SPConfig object. In order to do so you set the following
  242. setting::
  243. SAML_CONFIG_LOADER = 'python.path.to.your.callable'
  244. User attributes
  245. ---------------
  246. In the SAML 2.0 authentication process the Identity Provider (IdP) will
  247. send a security assertion to the Service Provider (SP) upon a successful
  248. authentication. This assertion contains attributes about the user that
  249. was authenticated. It depends on the IdP configuration what exact
  250. attributes are sent to each SP it can talk to.
  251. When such assertion is received on the Django side it is used to find a Django
  252. user and create a session for it. By default djangosaml2 will do a query on the
  253. User model with the USERNAME_FIELD_ attribute but you can change it to any
  254. other attribute of the User model. For example, you can do this lookup using
  255. the 'email' attribute. In order to do so you should set the following setting::
  256. SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'email'
  257. .. _USERNAME_FIELD: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD
  258. Please, use an unique attribute when setting this option. Otherwise
  259. the authentication process may fail because djangosaml2 will not know
  260. which Django user it should pick.
  261. If your main attribute is something inherently case-insensitive (such as
  262. an email address), you may set::
  263. SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP = '__iexact'
  264. (This is simply appended to the main attribute name to form a Django
  265. query. Your main attribute must be unique even given this lookup.)
  266. Another option is to use the SAML2 name id as the username by setting::
  267. SAML_USE_NAME_ID_AS_USERNAME = True
  268. You can configure djangosaml2 to create such user if it is not already in
  269. the Django database or maybe you don't want to allow users that are not
  270. in your database already. For this purpose there is another option you
  271. can set in the settings.py file::
  272. SAML_CREATE_UNKNOWN_USER = True
  273. This setting is True by default.
  274. ACS_DEFAULT_REDIRECT_URL = reverse_lazy('some_url_name')
  275. This setting lets you specify a URL for redirection after a successful
  276. authentication. Particularly useful when you only plan to use
  277. IdP initiated login and the IdP does not have a configured RelayState
  278. parameter. The default is ``/``.
  279. The other thing you will probably want to configure is the mapping of
  280. SAML2 user attributes to Django user attributes. By default only the
  281. User.username attribute is mapped but you can add more attributes or
  282. change that one. In order to do so you need to change the
  283. SAML_ATTRIBUTE_MAPPING option in your settings.py::
  284. SAML_ATTRIBUTE_MAPPING = {
  285. 'uid': ('username', ),
  286. 'mail': ('email', ),
  287. 'cn': ('first_name', ),
  288. 'sn': ('last_name', ),
  289. }
  290. where the keys of this dictionary are SAML user attributes and the values
  291. are Django User attributes.
  292. If you are using Django user profile objects to store extra attributes
  293. about your user you can add those attributes to the SAML_ATTRIBUTE_MAPPING
  294. dictionary. For each (key, value) pair, djangosaml2 will try to store the
  295. attribute in the User model if there is a matching field in that model.
  296. Otherwise it will try to do the same with your profile custom model. For
  297. multi-valued attributes only the first value is assigned to the destination field.
  298. Alternatively, custom processing of attributes can be achieved by setting the
  299. value(s) in the SAML_ATTRIBUTE_MAPPING, to name(s) of method(s) defined on a
  300. custom django User object. In this case, each method is called by djangosaml2,
  301. passing the full list of attribute values extracted from the <saml:AttributeValue>
  302. elements of the <saml:Attribute>. Among other uses, this is a useful way to process
  303. multi-valued attributes such as lists of user group names.
  304. For example:
  305. Saml assertion snippet::
  306. <saml:Attribute Name="groups" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
  307. <saml:AttributeValue>group1</saml:AttributeValue>
  308. <saml:AttributeValue>group2</saml:AttributeValue>
  309. <saml:AttributeValue>group3</saml:AttributeValue>
  310. </saml:Attribute>
  311. Custom User object::
  312. from django.contrib.auth.models import AbstractUser
  313. class User(AbstractUser):
  314. def process_groups(self, groups):
  315. // process list of group names in argument 'groups'
  316. pass;
  317. settings.py::
  318. SAML_ATTRIBUTE_MAPPING = {
  319. 'groups': ('process_groups', ),
  320. }
  321. Learn more about Django profile models at:
  322. https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
  323. Sometimes you need to use special logic to update the user object
  324. depending on the SAML2 attributes and the mapping described above
  325. is simply not enough. For these cases djangosaml2 provides a Django
  326. signal that you can listen to. In order to do so you can add the
  327. following code to your app::
  328. from djangosaml2.signals import pre_user_save
  329. def custom_update_user(sender=User, instance, attributes, user_modified, **kargs)
  330. ...
  331. return True # I modified the user object
  332. Your handler will receive the user object, the list of SAML attributes
  333. and a flag telling you if the user is already modified and need
  334. to be saved after your handler is executed. If your handler
  335. modifies the user object it should return True. Otherwise it should
  336. return False. This way djangosaml2 will know if it should save
  337. the user object so you don't need to do it and no more calls to
  338. the save method are issued.
  339. IdP setup
  340. =========
  341. Congratulations, you have finished configuring the SP side of the federation.
  342. Now you need to send the entity id and the metadata of this new SP to the
  343. IdP administrators so they can add it to their list of trusted services.
  344. You can get this information starting your Django development server and
  345. going to the http://localhost:8000/saml2/metadata url. If you have included
  346. the djangosaml2 urls under a different url prefix you need to correct this
  347. url.
  348. SimpleSAMLphp issues
  349. --------------------
  350. As of SimpleSAMLphp 1.8.2 there is a problem if you specify attributes in
  351. the SP configuration. When the SimpleSAMLphp metadata parser converts the
  352. XML into its custom php format it puts the following option::
  353. 'attributes.NameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'
  354. But it need to be replaced by this one::
  355. 'AttributeNameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'
  356. Otherwise the Assertions sent from the IdP to the SP will have a wrong
  357. Attribute Name Format and pysaml2 will be confused.
  358. Furthermore if you have a AttributeLimit filter in your SimpleSAMLphp
  359. configuration you will need to enable another attribute filter just
  360. before to make sure that the AttributeLimit does not remove the attributes
  361. from the authentication source. The filter you need to add is an AttributeMap
  362. filter like this::
  363. 10 => array(
  364. 'class' => 'core:AttributeMap', 'name2oid'
  365. ),
  366. Testing
  367. =======
  368. One way to check if everything is working as expected is to enable the
  369. following url::
  370. urlpatterns = patterns(
  371. '',
  372. # lots of url definitions here
  373. (r'^saml2/', include('djangosaml2.urls')),
  374. (r'^test/', 'djangosaml2.views.echo_attributes'),
  375. # more url definitions
  376. )
  377. Now if you go to the /test/ url you will see your SAML attributes and also
  378. a link to do a global logout.
  379. You can also run the unit tests with the following command::
  380. python tests/run_tests.py
  381. If you have `tox`_ installed you can simply call tox inside the root directory
  382. and it will run the tests in multiple versions of Python.
  383. .. _`tox`: http://pypi.python.org/pypi/tox
  384. FAQ
  385. ===
  386. **Why can't SAML be implemented as an Django Authentication Backend?**
  387. well SAML authentication is not that simple as a set of credentials you can
  388. put on a login form and get a response back. Actually the user password is
  389. not given to the service provider at all. This is by design. You have to
  390. delegate the task of authentication to the IdP and then get an asynchronous
  391. response from it.
  392. Given said that, djangosaml2 does use a Django Authentication Backend to
  393. transform the SAML assertion about the user into a Django user object.
  394. **Why not put everything in a Django middleware class and make our lifes
  395. easier?**
  396. Yes, that was an option I did evaluate but at the end the current design
  397. won. In my opinion putting this logic into a middleware has the advantage
  398. of making it easier to configure but has a couple of disadvantages: first,
  399. the middleware would need to check if the request path is one of the
  400. SAML endpoints for every request. Second, it would be too magical and in
  401. case of a problem, much harder to debug.
  402. **Why not call this package django-saml as many other Django applications?**
  403. Following that pattern then I should import the application with
  404. import saml but unfortunately that module name is already used in pysaml2.