Skip to main content

Django-staff-sso-client

CircleCI codecov PyPI PyPI - Python Version PyPI - Django Version

A Django client for staff-sso

Requirements

Python 3.9

Django>=4.2

Version 4+ of this package drops support for Django version 2.2.

For Django versions Django==2.2 install v3.1.1:

pip install django-staff-sso-client==3.1.1

Version 2+ of this package drops support for Django versions below 2.2.

For Django versions 1.11 <= Django < 2.2 install v1.0.1:

pip install django-staff-sso-client==1.0.1

Upgrade to version 3.0.0 considerations

The default ID field has been changed to email_user_id. Previously the user_id (guid) was the default field - see below for details on how to revert to user_id if needed.

MIGRATE_EMAIL_USER_ON_LOGIN logic has been removed.

Installation

pip install django-staff-sso-client

Configuration

Add the following to your settings file:

INSTALLED_APPS=[
    [...]
    'authbroker_client',
]
# authbroker config
AUTHBROKER_URL = 'speak-to-webops-team-for-access'
AUTHBROKER_CLIENT_ID = 'speak-to-webops-team-for-access'
AUTHBROKER_CLIENT_SECRET = 'speak-to-webops-team-for-access'
AUTHBROKER_STAFF_SSO_SCOPE = 'any-additional-scope-values'
AUTHBROKER_ANONYMOUS_PATHS = (Tuple/list of paths that should be unprotected)
AUTHBROKER_ANONYMOUS_URL_NAMES = (list of url names that should be unprotected)

Add the 'authbroker_client.backends.AuthbrokerBackend' authentication backend, e.g:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'authbroker_client.backends.AuthbrokerBackend',
]

If you use a custom authentication backend that subclasses authbroker_client.backends.AuthbrokerBackend, configure it with:

AUTHBROKER_AUTHENTICATION_BACKEND = (
    "your_app.backends.CustomAuthbrokerBackend"
)

This setting is optional. If omitted, the default backend authbroker_client.backends.AuthbrokerBackend will be used.

Add the LOGIN_URL ( it must be '/auth/login' )

LOGIN_URL = reverse_lazy('authbroker_client:login')

Add the LOGIN_REDIRECT_URL for e.g.

LOGIN_REDIRECT_URL = reverse_lazy('home_page')

Then finally add this to your main urls.py file:

path('auth/', include('authbroker_client.urls'))

or, if you're using Django<2:

url('^auth/', include('authbroker_client.urls', namespace='authbroker', app_name='authbroker_client'))

You should now have an /auth/login/ URL which directs users through the staff-sso login flow. Once a user is authenticated via staff-sso (and chosen identify provider), they will be redirected back to your application. A local django user with a matching email address will then be logged in. The user entry will be created if it does not already exist in the database.

Once authenticated, the user will be redirected to settings.LOGIN_REDIRECT_URL

Use the django @login_required decorator to protect individual views, or if you want to protect all views use this middleware:

MIDDLEWARE = [
    [...]
    'authbroker_client.middleware.ProtectAllViewsMiddleware',
]

For local development with https://github.com/uktrade/mock-sso, where it runs under a port 8001 as a Docker service called sso for example, add the following to your settings file.

AUTHBROKER_INTERNAL_URL = 'http://sso:8001'

For remote deployments, AUTHBROKER_INTERNAL_URL can be ommitted or equal to AUTHBROKER_URL.

Change the default user id field

Staff-sso maintains two unique user ids for each user: the email_user_id field, which is in an email format [NOTE: it is purely a unique id, not a valid email address] and the user_id field, which is a GUID. By default (from version 3.0.0 onwards) django-staff-sso-client identifies users based on the email_user_id field. This is the preferred option for most cases. If however, you need to use the user_id field, then add this to your settings.py file:

AUTHBROKER_USE_USER_ID_GUID = True

When creating new users django-staff-sso-client attempts to store the user id in the User.USERNAME_FIELD field. With the stock django model this will be the username field. If you use a custom user model you can override this field as needed, for example:

class YourCustomUserModel(...):
  USERNAME_FIELD = 'sso_email_id'

NOTE: As per django's documentation, the USERNAME_FIELD should be the user model's primary key.

Change the user creation mapping

Here's an example staff-sso profile, which is available at the point of user creation:

{
    'user_id': '6fa3b542-9a6f-4fc3-a248-168596572999',   
    'email_user_id': 'john.smith-6fa3b542@id.trade.gov.uk',    
    'email': 'john.smith@someplace.gov.uk',
    'contact_email': 'john.smith@someemail.com',
    'related_emails': [   'jsmith@someotherplace.com',
                          'me@johnsmith.com'],  
    'first_name': 'John',
    'last_name': 'Smith',                
    'groups': [ ... ],                    
    'permitted_applications': [ ... ],
    'access_profiles': [ ... ]
}

The default mapping is:

{
      'email': profile['email'],
      'first_name': profile['first_name'],
      'last_name': profile['last_name'],
}

You can change this default mapping by subclassing the authentication backend authbroker_client.backends.AuthbrokerBackend and overriding the user_create_mapping method.

Here's an example:

from authbroker_client.backends import AuthbrokerBackend


class CustomAuthbrokerBackend(AuthbrokerBackend):
    def user_create_mapping(self, profile):
        return {
            "is_active": True,
            "first_name": profile["first_name"],
            "last_name": profile["last_name"],
        }

Exclude page from SSO Auth check

In order to allow anonymous access to a page on a site protected using this client, add the following setting to your Django settings file:

AUTHBROKER_ANONYMOUS_PATHS = ('anonymous/path',)

Alternatively, you can use the AUTHBROKER_ANONYMOUS_URL_NAMES setting to specify a list of url names.

AUTHBROKER_ANONYMOUS_URL_NAMES = ('url-name',)

Multiple concurrent auth flows and cache storage

This new logic, which requies an opt-in by setting AUTHBROKER_USE_CACHE_STATE_STORE in your project's settings file, attempts to resolve potential errors caused by multiple concurrent auth flows. Two potential failure modes are:

  1. The state key is clobbered by concurrent auth flows.
  2. In /auth/callback/, the django.contrib.auth.login() funcion cycles the session idy to prevent session fixation attacks. If another flow sends the old session id via a cookie, it may result in an empty session and missing state key.

To remediate this the state value is incorporated into the key (e.g. f'_oauth_{state}') and the state value is stored in the cache, instead of in session. Also, if request.user.is_authenticated is True, the /auth/callback/ process short circuits the Oauth2 token exchange process.

Apps that use the cache need to use a cache backend that persists across processes such as the RedisCache. The default LocMemCache, which should only be used for local development, will break your SSO integration.

Use with UKTrade mock-sso package

It is possible to configure this package to work with the mock-sso service.

Mock SSO requires that you provide a non-standard parameter in the query string of the initial GET call of the OAuth flow. (See the mock-sso docs for more detail.)

This parameter is called code. Any services which use THIS library (django-mock-sso-client) could need to undertake automated tests of a stack which uses Staff SSO for downstream components (example: testing an app which in return requires access to another service's API, both of which use SSO for authentication).

For circumstances like these you will need to prime mock-sso with this code parameter.

This is achieved by changing the Django settings for the app which is importing THIS library. In those settings, add:

TEST_SSO_PROVIDER_SET_RETURNED_ACCESS_TOKEN = 'someCode'

where 'someCode' will then be provided as the 'access token' during the OAuth callback to mock-sso. (Again, see the mock-sso docs for more detail.)

Release files for django-staff-sso-client 5.3.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-staff-sso-client 5.3.4
File Size Uploaded
django_staff_sso_client-5.3.4.tar.gz 19.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-staff-sso-client 5.3.4
File Interpreter ABI Platform
django_staff_sso_client-5.3.4-py3-none-any.whl Python 3 none any Details

Total release size: 39.7 kB

Release files / django_staff_sso_client-5.3.4.tar.gz

Download URL django_staff_sso_client-5.3.4.tar.gz
Size 19.2 kB
Tags Source
SHA-256 checksum
How to use checksums
32a111454d9a73c78d6b8b58219b6de9bcee47eefdc84b248ea386e1590c77b9
BLAKE2b-256 checksum
How to use checksums
a34b2ea1368f6f199e96258ad37d48a0391855922bbde89936b8c25115b02734
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.6

Release files / django_staff_sso_client-5.3.4-py3-none-any.whl

Download URL django_staff_sso_client-5.3.4-py3-none-any.whl
Size 20.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8cd4eda8d5a23ac475a2e0f67deba448ee086c24a3e5eeec678e9451cbbc59d7
BLAKE2b-256 checksum
How to use checksums
2da15e473072f02c7cc2bbcdbd4f73a8b55d0b9d16366b1aa29e1f23af41ef88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.6

Release history Release notifications | RSS feed

This release

5.3.4 This release

2 release files

5.3.3

2 release files

5.3.2

2 release files

5.3.1

2 release files

5.3.0

2 release files

5.2.1

2 release files

5.2.0

2 release files

5.1.0

2 release files

5.0.1

2 release files

5.0.0

2 release files

4.4.1

2 release files

4.4.0

2 release files

4.3.0

2 release files

4.2.2

2 release files

4.2.1

2 release files

4.2.0

2 release files

4.1.1

2 release files

4.0.1

2 release files

4.0.0

2 release files

3.1.1

2 release files

3.1.0

1 release file

3.0.0

1 release file

2.2.1

1 release file

2.2.0

1 release file

2.1.0

1 release file

2.0.1

1 release file

2.0.0

1 release file

1.0.1

1 release file

1.0.0

1 release file

0.4.0

1 release file

0.3.1

1 release file

0.3.0

1 release file

0.2.0

1 release file

0.1.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page