README.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. # attributes that this project need to identify a user
  149. 'required_attributes': ['uid'],
  150. # attributes that may be useful to have but not required
  151. 'optional_attributes': ['eduPersonAffiliation'],
  152. # in this section the list of IdPs we talk to are defined
  153. 'idp': {
  154. # we do not need a WAYF service since there is
  155. # only an IdP defined here. This IdP should be
  156. # present in our metadata
  157. # the keys of this dictionary are entity ids
  158. 'https://localhost/simplesaml/saml2/idp/metadata.php': {
  159. 'single_sign_on_service': {
  160. saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SSOService.php',
  161. },
  162. 'single_logout_service': {
  163. saml2.BINDING_HTTP_REDIRECT: 'https://localhost/simplesaml/saml2/idp/SingleLogoutService.php',
  164. },
  165. },
  166. },
  167. },
  168. },
  169. # where the remote metadata is stored
  170. 'metadata': {
  171. 'local': [path.join(BASEDIR, 'remote_metadata.xml')],
  172. },
  173. # set to 1 to output debugging information
  174. 'debug': 1,
  175. # Signing
  176. 'key_file': path.join(BASEDIR, 'mycert.key'), # private part
  177. 'cert_file': path.join(BASEDIR, 'mycert.pem'), # public part
  178. # Encryption
  179. 'encryption_keypairs': [{
  180. 'key_file': path.join(BASEDIR, 'my_encryption_key.key'), # private part
  181. 'cert_file': path.join(BASEDIR, 'my_encryption_cert.pem'), # public part
  182. }],
  183. # own metadata settings
  184. 'contact_person': [
  185. {'given_name': 'Lorenzo',
  186. 'sur_name': 'Gil',
  187. 'company': 'Yaco Sistemas',
  188. 'email_address': 'lgs@yaco.es',
  189. 'contact_type': 'technical'},
  190. {'given_name': 'Angel',
  191. 'sur_name': 'Fernandez',
  192. 'company': 'Yaco Sistemas',
  193. 'email_address': 'angel@yaco.es',
  194. 'contact_type': 'administrative'},
  195. ],
  196. # you can set multilanguage information here
  197. 'organization': {
  198. 'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')],
  199. 'display_name': [('Yaco', 'es'), ('Yaco', 'en')],
  200. 'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')],
  201. },
  202. 'valid_for': 24, # how long is our metadata valid
  203. }
  204. .. note::
  205. Please check the `PySAML2 documentation`_ for more information about
  206. these and other configuration options.
  207. .. _`PySAML2 documentation`: http://pysaml2.readthedocs.io/en/latest/
  208. There are several external files and directories you have to create according
  209. to this configuration.
  210. The xmlsec1 binary was mentioned in the installation section. Here, in the
  211. configuration part you just need to put the full path to xmlsec1 so PySAML2
  212. can call it as it needs.
  213. The ``attribute_map_dir`` points to a directory with attribute mappings that
  214. are used to translate user attribute names from several standards. It's usually
  215. safe to just copy the default PySAML2 attribute maps that you can find in the
  216. ``tests/attributemaps`` directory of the source distribution.
  217. The ``metadata`` option is a dictionary where you can define several types of
  218. metadata for remote entities. Usually the easiest type is the ``local`` where
  219. you just put the name of a local XML file with the contents of the remote
  220. entities metadata. This XML file should be in the SAML2 metadata format.
  221. The ``key_file`` and ``cert_file`` options reference the two parts of a
  222. standard x509 certificate. You need it to sign your metadata. For assertion
  223. encryption/decryption support please configure another set of ``key_file`` and
  224. ``cert_file``, but as inner attributes of ``encryption_keypairs`` option.
  225. .. note::
  226. Check your openssl documentation to generate a test certificate but don't
  227. forget to order a real one when you go into production.
  228. Custom and dynamic configuration loading
  229. ........................................
  230. By default, djangosaml2 reads the pysaml2 configuration options from the
  231. SAML_CONFIG setting but sometimes you want to read this information from
  232. another place, like a file or a database. Sometimes you even want this
  233. configuration to be different depending on the request.
  234. Starting from djangosaml2 0.5.0 you can define your own configuration
  235. loader which is a callable that accepts a request parameter and returns
  236. a saml2.config.SPConfig object. In order to do so you set the following
  237. setting::
  238. SAML_CONFIG_LOADER = 'python.path.to.your.callable'
  239. User attributes
  240. ---------------
  241. In the SAML 2.0 authentication process the Identity Provider (IdP) will
  242. send a security assertion to the Service Provider (SP) upon a successful
  243. authentication. This assertion contains attributes about the user that
  244. was authenticated. It depends on the IdP configuration what exact
  245. attributes are sent to each SP it can talk to.
  246. When such assertion is received on the Django side it is used to find a Django
  247. user and create a session for it. By default djangosaml2 will do a query on the
  248. User model with the USERNAME_FIELD_ attribute but you can change it to any
  249. other attribute of the User model. For example, you can do this lookup using
  250. the 'email' attribute. In order to do so you should set the following setting::
  251. SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'email'
  252. .. _USERNAME_FIELD: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD
  253. Please, use an unique attribute when setting this option. Otherwise
  254. the authentication process may fail because djangosaml2 will not know
  255. which Django user it should pick.
  256. If your main attribute is something inherently case-insensitive (such as
  257. an email address), you may set::
  258. SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP = '__iexact'
  259. (This is simply appended to the main attribute name to form a Django
  260. query. Your main attribute must be unique even given this lookup.)
  261. Another option is to use the SAML2 name id as the username by setting::
  262. SAML_USE_NAME_ID_AS_USERNAME = True
  263. You can configure djangosaml2 to create such user if it is not already in
  264. the Django database or maybe you don't want to allow users that are not
  265. in your database already. For this purpose there is another option you
  266. can set in the settings.py file::
  267. SAML_CREATE_UNKNOWN_USER = True
  268. This setting is True by default.
  269. ACS_DEFAULT_REDIRECT_URL = reverse_lazy('some_url_name')
  270. This setting lets you specify a URL for redirection after a successful
  271. authentication. Particularly useful when you only plan to use
  272. IdP initiated login and the IdP does not have a configured RelayState
  273. parameter. The default is ``/``.
  274. The other thing you will probably want to configure is the mapping of
  275. SAML2 user attributes to Django user attributes. By default only the
  276. User.username attribute is mapped but you can add more attributes or
  277. change that one. In order to do so you need to change the
  278. SAML_ATTRIBUTE_MAPPING option in your settings.py::
  279. SAML_ATTRIBUTE_MAPPING = {
  280. 'uid': ('username', ),
  281. 'mail': ('email', ),
  282. 'cn': ('first_name', ),
  283. 'sn': ('last_name', ),
  284. }
  285. where the keys of this dictionary are SAML user attributes and the values
  286. are Django User attributes.
  287. If you are using Django user profile objects to store extra attributes
  288. about your user you can add those attributes to the SAML_ATTRIBUTE_MAPPING
  289. dictionary. For each (key, value) pair, djangosaml2 will try to store the
  290. attribute in the User model if there is a matching field in that model.
  291. Otherwise it will try to do the same with your profile custom model. For
  292. multi-valued attributes only the first value is assigned to the destination field.
  293. Alternatively, custom processing of attributes can be achieved by setting the
  294. value(s) in the SAML_ATTRIBUTE_MAPPING, to name(s) of method(s) defined on a
  295. custom django User object. In this case, each method is called by djangosaml2,
  296. passing the full list of attribute values extracted from the <saml:AttributeValue>
  297. elements of the <saml:Attribute>. Among other uses, this is a useful way to process
  298. multi-valued attributes such as lists of user group names.
  299. For example:
  300. Saml assertion snippet::
  301. <saml:Attribute Name="groups" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
  302. <saml:AttributeValue>group1</saml:AttributeValue>
  303. <saml:AttributeValue>group2</saml:AttributeValue>
  304. <saml:AttributeValue>group3</saml:AttributeValue>
  305. </saml:Attribute>
  306. Custom User object::
  307. from django.contrib.auth.models import AbstractUser
  308. class User(AbstractUser):
  309. def process_groups(self, groups):
  310. // process list of group names in argument 'groups'
  311. pass;
  312. settings.py::
  313. SAML_ATTRIBUTE_MAPPING = {
  314. 'groups': ('process_groups', ),
  315. }
  316. Learn more about Django profile models at:
  317. https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
  318. Sometimes you need to use special logic to update the user object
  319. depending on the SAML2 attributes and the mapping described above
  320. is simply not enough. For these cases djangosaml2 provides a Django
  321. signal that you can listen to. In order to do so you can add the
  322. following code to your app::
  323. from djangosaml2.signals import pre_user_save
  324. def custom_update_user(sender=User, instance, attributes, user_modified, **kargs)
  325. ...
  326. return True # I modified the user object
  327. Your handler will receive the user object, the list of SAML attributes
  328. and a flag telling you if the user is already modified and need
  329. to be saved after your handler is executed. If your handler
  330. modifies the user object it should return True. Otherwise it should
  331. return False. This way djangosaml2 will know if it should save
  332. the user object so you don't need to do it and no more calls to
  333. the save method are issued.
  334. IdP setup
  335. =========
  336. Congratulations, you have finished configuring the SP side of the federation.
  337. Now you need to send the entity id and the metadata of this new SP to the
  338. IdP administrators so they can add it to their list of trusted services.
  339. You can get this information starting your Django development server and
  340. going to the http://localhost:8000/saml2/metadata url. If you have included
  341. the djangosaml2 urls under a different url prefix you need to correct this
  342. url.
  343. SimpleSAMLphp issues
  344. --------------------
  345. As of SimpleSAMLphp 1.8.2 there is a problem if you specify attributes in
  346. the SP configuration. When the SimpleSAMLphp metadata parser converts the
  347. XML into its custom php format it puts the following option::
  348. 'attributes.NameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'
  349. But it need to be replaced by this one::
  350. 'AttributeNameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'
  351. Otherwise the Assertions sent from the IdP to the SP will have a wrong
  352. Attribute Name Format and pysaml2 will be confused.
  353. Furthermore if you have a AttributeLimit filter in your SimpleSAMLphp
  354. configuration you will need to enable another attribute filter just
  355. before to make sure that the AttributeLimit does not remove the attributes
  356. from the authentication source. The filter you need to add is an AttributeMap
  357. filter like this::
  358. 10 => array(
  359. 'class' => 'core:AttributeMap', 'name2oid'
  360. ),
  361. Testing
  362. =======
  363. One way to check if everything is working as expected is to enable the
  364. following url::
  365. urlpatterns = patterns(
  366. '',
  367. # lots of url definitions here
  368. (r'^saml2/', include('djangosaml2.urls')),
  369. (r'^test/', 'djangosaml2.views.echo_attributes'),
  370. # more url definitions
  371. )
  372. Now if you go to the /test/ url you will see your SAML attributes and also
  373. a link to do a global logout.
  374. You can also run the unit tests with the following command::
  375. python tests/run_tests.py
  376. If you have `tox`_ installed you can simply call tox inside the root directory
  377. and it will run the tests in multiple versions of Python.
  378. .. _`tox`: http://pypi.python.org/pypi/tox
  379. FAQ
  380. ===
  381. **Why can't SAML be implemented as an Django Authentication Backend?**
  382. well SAML authentication is not that simple as a set of credentials you can
  383. put on a login form and get a response back. Actually the user password is
  384. not given to the service provider at all. This is by design. You have to
  385. delegate the task of authentication to the IdP and then get an asynchronous
  386. response from it.
  387. Given said that, djangosaml2 does use a Django Authentication Backend to
  388. transform the SAML assertion about the user into a Django user object.
  389. **Why not put everything in a Django middleware class and make our lifes
  390. easier?**
  391. Yes, that was an option I did evaluate but at the end the current design
  392. won. In my opinion putting this logic into a middleware has the advantage
  393. of making it easier to configure but has a couple of disadvantages: first,
  394. the middleware would need to check if the request path is one of the
  395. SAML endpoints for every request. Second, it would be too magical and in
  396. case of a problem, much harder to debug.
  397. **Why not call this package django-saml as many other Django applications?**
  398. Following that pattern then I should import the application with
  399. import saml but unfortunately that module name is already used in pysaml2.