Go to file
Benjamin Dauvergne 7f58bf9c66
gitea/django-mellon/pipeline/head This commit looks good Details
misc: do not update Issuer uselessly (#86976)
2024-02-15 09:59:47 +01:00
debian misc: require django 3.2 (#75442) 2023-03-16 17:15:06 +01:00
mellon misc: do not update Issuer uselessly (#86976) 2024-02-15 09:59:47 +01:00
tests misc: do not read not_on_or_after if session is not loaded (#86451) 2024-02-01 16:17:22 +01:00
.git-blame-ignore-revs misc: update git-blame-ignore-revs to ignore quote changes (#79788) 2023-08-16 10:31:30 +02:00
.gitignore Add .gitignore 2015-04-29 16:38:13 +02:00
.pre-commit-config.yaml misc: add pre commit hook to force single quotes (#79788) 2023-08-16 10:31:29 +02:00
COPYING first commit 2014-04-30 14:34:39 +02:00
Changelog release 1.9 2019-10-05 13:19:26 +02:00
Jenkinsfile ci: build deb package for bookworm (#78968) 2023-06-23 17:28:33 +02:00
MANIFEST.in release 1.2.26 2016-04-27 10:03:09 +02:00
README misc: change django-upgrade target version to 3.2 (#75442) 2023-03-16 17:18:53 +01:00
getlasso.sh add tox.ini to test on django 1.7, 1.8, 1.9 and with sqlite and pg 2016-02-26 18:09:11 +01:00
getlasso3.sh misc: replace use of distutils.sysconfig by sysconfig in getlasso3.sh 2022-10-07 12:45:52 +02:00
jenkins.sh add a jenkins.sh 2017-03-22 23:54:51 +01:00
pylint.sh ci: remove django 2.2 targets (#86402) 2024-01-31 22:07:21 +01:00
setup.py misc: apply double-quote-string-fixer (#79788) 2023-08-16 10:31:30 +02:00
testsettings.py tests: vary dbname on each test run (#84947) 2023-12-19 18:42:16 +01:00
tox.ini ci: use pytest-freezer to mute warnings (#86402) 2024-01-31 22:08:16 +01:00

README

django-mellon
=============

SAML 2.0 authentication for Django

Usage
=====

You need to have the Python binding for the Lasso library installed, you can
find source and package for Debian on http://lasso.entrouvert.org/download/.

Add mellon to your installed apps::

    INSTALLED_APPS = (
       ...
       'mellon',
    )

Add the SAMLBacked to your authentication backends::

    AUTHENTICATION_BACKENDS = (
        ...
        'mellon.backends.SAMLBackend',
    )

Add mellon urls to your urls::

    urlpatterns = patterns('',
        ...
        url(r'^/accounts/mellon/', include('mellon.urls')),
    )

Please note that from django 3.2 onwards, a registered AdminSite app embeds a
url-routing catch-all option (AdminSite.final_catch_all_view) that is activated
by default and that may collide with the django-mellon app if its url routing
is declared before mellon's url routing.

If SAML 2.0 should be your only authentication method you can define `mellon_login` as you main `LOGIN_URL`::

    LOGIN_URL = 'mellon_login'
    LOGOUT_URL = 'mellon_logout'

Your metadata will be downloadable through HTTP on 

    http://whatever.example.net/accounts/mellon/metadata

If your identity provider ask for your assertion consumer URL it's on

    http://whatever.example.net/accounts/mellon/login

If your identity provider ask for your logout URL it's on

    http://whatever.example.net/accounts/mellon/logout

Session
=======

After an authentication attributes are stored in the session using a
dictionary, the key is `mellon_session`. The dictionary contains:

 - issuer: the EntityID of the identity provider
 - name_id_content: the value of the NameID
 - name_id_format: the format of the NameID
 - authn_instant: the ISO8601 date of the authentication on the identity provider, optional.
 - session_not_on_or_after: the ISO8691 date after which the local
   session should be closed. Note that we automatically set the
   expiration of the Django session to this value if it's available.
 - authn_context_class_ref: the authentication method of the current
   authentication on the identity provider. You can restrict
   authorized authentication methods using the setting
   `MELLON_AUTHN_CLASSREF`.
 - all attributes extracted from the assertion.

Settings
========

All generic setting apart from `MELLON_IDENTITY_PROVIDERS` can be
overridden in the identity provider settings by removing the
`MELLON_` prefix.

MELLON_IDENTITY_PROVIDERS
-------------------------

A list of dictionaries, they must contain at least one of the keys `METADATA`
(inline copy of the identity provider metadata), `METADATA_URL` URL of the IdP
metadata file, or `METADATA_PATH` an absolute path to the IdP metadata file..
All other keys are override of generic settings.

When using an URL, the URL is automatically cached in the `MEDIA_ROOT`
directory of your application in the directory named `mellon_metadata_cache`.
If you restart the application and the URL is unavailable, the file cache will
be used. The cache will be refreshed every `MELLON_METADATA_CACHE_TIME` seconds.
If the HTTP retrieval of the metadata URL takes longer thant
`MELLON_METADATA_HTTP_TIMEOUT` seconds, retrieval will be skipped.

When the cache is already loaded, retrievals are done in the background by a
thread.

When using a local absolute path, the metadata is reloaded each time the
modification time of the file is superior to the last time it was loaded.

MELLON_PUBLIC_KEYS
------------------

List of public keys of this service provider, add multiple keys for
doing key roll-over

MELLON_PRIVATE_KEY
------------------

The PKCS#8 PEM encoded private key. If neither MELLON_PRIVATE_KEYS and
MELLON_PRIVATE_KEY are set, request will not be signed.

MELLON_PRIVATE_KEY_PASSWORD
---------------------------

Password for the private key if needed, default is None

MELLON_PRIVATE_KEYS
-------------------

A list of private keys contained in strings (same format ass
MELLON_PRIVATE_KEY) or of tuple paris (private_key, private_key_password). If
MELLON_PRIVATE_KEY is None, the first key in MELLON_PRIVATE_KEYS will be used
to sign messages. Other keys are only for decrypting encrypted assertions.  If
the same key appear in MELLON_PRIVATE_KEY and MELLON_PRIVATE_KEYS it will be
ignored the second time. If neither MELLON_PRIVATE_KEYS and MELLON_PRIVATE_KEY
are set, request will not be signed.

MELLON_NAME_ID_FORMATS
----------------------

NameID formats to advertise in the metadata file, default is ().

MELLON_NAME_ID_POLICY_FORMAT
----------------------------

The NameID format to request, default is None.

MELLON_FORCE_AUTHN
------------------

Whether to force authentication on each authencation request,
default is False.

MELLON_ADAPTER
--------------

A list of class providings methods handling SAML authorization, user
lookup and provisioning. Optional methods on theses classes are

 - authorize(idp, saml_attributes) -> boolean

   If any adapter returns False, the authentication is refused. It's
   possible to raise PermissionDenied to show a specific message on
   the login interface.

 - lookup_user(idp, saml_attributes) -> User / None

   Each adapter is called in the order of the settings, the first
   return value which is not None is kept as the authenticated user.

 - provision(user, idp, saml_attributes -> None

   This method is there to fill an existing user fields with data
   from the SAML attributes or to provision any kind of object in the
   application.

Settings of the default adapter
===============================

The following settings are used by the default adapter
`mellon.adapters.DefaulAdapter` if you use your own adapter you can
ignore them. If your adapter inherit from the default adapter those
settings can still be applicable.

MELLON_REALM
------------

The default realm to associate to user created with the default
adapter, default is 'saml'.

MELLON_PROVISION
----------------

Whether to create user if their username does not already exists,
default is True.

MELLON_USERNAME_TEMPLATE
------------------------

The template to build and/or retrieve a user from its username based
on received attributes, the syntax is the one from the str.format()
method of Python. Available variables are:

 - realm
 - idp (current setting for the idp issuing the assertion)
 - attributes

The default value is `{attributes{name_id_content]}@realm`.

Another example could be `{atttributes[uid][0]}` to set the passed
username as the username of the newly created user.

MELLON_ATTRIBUTE_MAPPING
------------------------

Maps templates based on SAML attributes to field of the user model.
Default is {}. To copy standard LDAP attributes into your Django user
model could for example do that::

    MELLON_ATTRIBUTE_MAPPING = {
        'email': '{attributes[mail][0]',
        'first_name': '{attributes[gn][0]}',
        'last_name': '{attributes[sn][0]}',
    }

MELLON_SUPERUSER_MAPPING
------------------------

Attributes superuser flags to user if a SAML attribute contains a given value,
default is {}. Ex.::

    MELLON_SUPERUSER_MAPPING = {
        'roles': 'Admin',
    }

MELLON_AUTHN_CLASSREF
---------------------

Authorized authentication class references, default is (). Empty
value means everything is authorized. Authentication class reference
must be obtained from your identity provider but SHOULD come from the
SAML 2.0 specification.

MELLON_GROUP_ATTRIBUTE
----------------------

Name of the SAML attribute to map to Django group names, default is None. Ex.::

   MELLON_GROUP_ATTRIBUTE = 'role'

MELLON_CREATE_GROUP
-------------------

Whether to create group or only assign existing groups, default is True.

MELLON_ERROR_URL
----------------

URL for the continue link when authentication fails, default is
None. If not ERROR_URL is None, the RelayState is used. If there is
no RelayState, the LOGIN_REDIRECT_URL, which defaults to /, is used.

MELLON_ERROR_REDIRECT_AFTER_TIMEOUT
-----------------------------------

Timeout in seconds before automatically redirecting the user to the
continue URL when authentication has failed. Default is 120 seconds.

MELLON_VERIFY_SSL_CERTIFICATE
-----------------------------

Verify SSL certificate when doing HTTP requests, used when resolving artifacts.
Default is True.

MELLON_TRANSIENT_FEDERATION_ATTRIBUTE
-------------------------------------

Name of an attribute to use in replacement of the NameID content when the NameID
format is transient. Without it no login using a transient NameID can occur with
the default adapter.
Default is None.

MELLON_DEFAULT_ASSERTION_CONSUMER_BINDING
-----------------------------------------

Should be post or artifact. Default is post. You can refer to the SAML 2.0
specification to learn the difference.

MELLON_LOOKUP_BY_ATTRIBUTES
---------------------------

Allow looking for user with some SAML attributes if the received NameID is
still unknown. It must be a list of dictionnaries with two mandatory keys
`user_field` and `saml_attribute`. The optionnal key `ignore-case` should be a
boolean indicating if the match is case-insensitive (default is to respect the
case).

Each dictionnary is a rule for linking, applying all the rules should only
return one user, the boolean operator OR is applied between the rules.

So for example if you received a SAML attribute named `email` and you want to
link user with the same email you would configured it like that::

   MELLON_LOOKUP_BY_ATTRIBUTES = [
       {
           'saml_attribute': 'email',
           'user_field': 'email',
       }
   ]

The targeted user(s) field(s) should be as much as possible unique
individually, if not django-mellon will refuse to link multiple users matching
the rules.

MELLON_METADATA_CACHE_TIME
--------------------------

When using METADATA_URL to reference a metadata file, it's the duration in
secondes between refresh of the metadata file. Default is 3600 seconds, 1 hour.

MELLON_METADATA_HTTP_TIMEOUT
----------------------------

Timeout in seconds for HTTP call made to retrieve metadata files. Default is 10
seconds.

MELLON_ASSERTION_CONSUMER_BINDINGS
----------------------------------

The list of supported assertion consumer bindings. Default is::

    ['post', 'artifact']

Tests
=====

Unit tests are written using pytest and launched using tox, and can be run with:

   tox

Code Style
==========

black is used to format the code, using thoses parameters:

    black --target-version py37 --skip-string-normalization --line-length 110

There is .pre-commit-config.yaml to use pre-commit to automatically run black
before commits. (execute `pre-commit install` to install the git hook.)

isort is used to format the imports, using those parameter:

    isort --profile black --line-length 110

pyupgrade is used to automatically upgrade syntax, using those parameters:

    pyupgrade --keep-percent-format --py37-plus

djhtml is used to automatically indent html files, using those parameters:

    djhtml --tabwidth 2

django-upgrade is used to automatically upgrade Django syntax, using those parameters:

    django-upgrade --target-version 3.2

There is .pre-commit-config.yaml to use pre-commit to automatically run these tools
before commits. (execute `pre-commit install` to install the git hook.)

Remarks
=======

To honor the SessionNotOnOrAfter attribute sent by an IdP you must use a specific SessionEngine,
only db and cached_db are supported currently, the equivalent session engines are:

    mellon.sessions_backends.db

and

    mellon.sessions_backends.cached_db