README 17 KB

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