Package: django-helusers-turku
Django app for City of Helsinki user infrastructureDjango-helusers is your friendly app for bolting authentication into Django projects for City of Helsinki. Authentication schemes are based onOAuth2andOpenID Connect (OIDC).A baselineUsermodel is provided that can be used with the various authentication use cases that are supported. The model supports mapping from AD groups to Django groups based on the authentication data.Additionally there areoptionalfunctionalities that can be used as needed.Functionalities for server needing (API) access token verification:For servers using Django REST FrameworkFor servers not using Django REST FrameworkFunctionalities for server needing to authenticate against OIDC or OAuth2 server:support Django session login against OIDC or OAuth2 server, including Helsinki Tunnistus service and Azure ADaugmented login template for Django admin, adding OIDC/OAuth2 login buttonAdding django-helusers your Django projectAdddjango-helusersin your project's dependencies.Some optional features ofdjango-helusershave additional dependencies.
These are mentioned in their relevant sections.Adding django-helusers Django appsDjango-helusers provides two Django apps:HelusersConfigprovides the
models and templates needed for helusers to work andHelusersAdminConfigreconfigures Django admin to work with helusers.Before adding the apps, you will need to removedjango.contrib.admin, asHelusersAdminConfigis implementation of same functionality. You will getdjango.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin-error, if you forget this step.Then proceed by adding these apps to yourINSTALLED_APPSin settings.py:INSTALLED_APPS=('helusers.apps.HelusersConfig','helusers.apps.HelusersAdminConfig',...)Us usual withINSTALLED_APPS, ordering matters.HelusersConfigmust come
beforeHelusersAdminConfigand anything else providing admin templates.
Unless, of course, you wish to override the admin templates provided here.One possible gotcha is, if you've added custom views to admin without
forwarding context fromeach_contextto the your template.  Helusers
templates expect variables fromeach_contextand will break if they are
missing.Adding user modelhelusers provides a baseline user model adding fields for Helsinki
specific information. As per Djangobest practiceyou should subclass this model to make future customization easier:# users/models.pyfromhelusers.modelsimportAbstractUserclassUser(AbstractUser):passand reference it in settings.py:# myproject/settings.pyAUTH_USER_MODEL='users.User'Optional featuresDjango REST Framework API authentication using JWTIf you have a REST API implemented using Django REST Framework and you want to authorize access to your API using JWTs, then this might be useful to you.API token authentication is a stateless authentication method, where every request is
authenticated by checking the signature of the included JWT token. It still
creates a persistent Django user, which is updated with the information
from the token with every request.Includedrf-oidc-authin your project's dependencies.Configure REST framework to use theApiTokenAuthenticationclass insettings.py:REST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':('helusers.oidc.ApiTokenAuthentication',),}Set your deployment-specific variables inlocal_settings.py, e.g.:OIDC_API_TOKEN_AUTH={# Audience that must be present in the token for the request to be# accepted. Value must be agreed between your SSO service and your# application instance. Essentially this allows your application to# know that the token in meant to be used with it.'AUDIENCE':'https://api.hel.fi/auth/projects',# Who we trust to sign the tokens. The library will request the# public signature keys from standard locations below this URL'ISSUER':'https://api.hel.fi/sso/openid'# The following can be used if you need certain OAuth2 scopes# for any functionality of the API. The request will be denied# if scopes starting with API_SCOPE_PREFIX are not present# in the token claims. Usually this is not needed, as checking# the audience is enough.'REQUIRE_API_SCOPE_FOR_AUTHENTICATION':True,'API_SCOPE_PREFIX':'projects',}API authentication using JWT in any setupIf you want to authorize access to your API using JWTs, but you are not using Django REST Framework, then this might be useful to you.API token authentication is a stateless authentication method, where every request is authenticated by checking the signature of the included JWT token.
It still creates a persistent Django user, which is updated with the information from the token with every request.Django-helusers contains ahelusers.oidc.RequestJWTAuthenticationclass.
It has a method calledauthenticatethat takes aDjango HttpRequestas an argument, looks for a JWT from that request and performs authentication.
User of this class can use it in any way they need to perform authentication and/or authorization.
Check the class documentation for more details.Some settings are needed (and some are optional) that affect how theRequestJWTAuthenticationclass works.OIDC_API_TOKEN_AUTH={# Audience that must be present in the token for it to be# accepted. Value must be agreed between your SSO service and your# application instance. Essentially this allows your application to# know that the token is meant to be used with it.# RequestJWTAuthentication supports multiple acceptable audiences,# so this setting can also be a list of strings.# This setting is required.'AUDIENCE':'https://api.hel.fi/auth/projects',# Who we trust to sign the tokens. The library will request the# public signature keys from standard locations below this URL.# RequestJWTAuthentication supports multiple issuers, so this# setting can also be a list of strings.# Default is https://tunnistamo.hel.fi.'ISSUER':'https://api.hel.fi/sso/openid'# The following can be used if you need certain scopes for any# functionality of the API. Usually this is not needed, as checking# the audience is enough. Default is False.'REQUIRE_API_SCOPE_FOR_AUTHENTICATION':True,# The name of the claim that is used to read in the scopes from the JWT.# Default is https://api.hel.fi/auth.'API_AUTHORIZATION_FIELD':'scope_field',# The request will be denied if scopes don't contain anything starting# with the value provided here.'API_SCOPE_PREFIX':'projects',# In order to do the authentication RequestJWTAuthentication needs# some facts from the authorization server, mainly its public keys for# verifying the JWT's signature. This setting controls the time how long# authorization server configuration and public keys are "remembered".# The value is in seconds. Default is 24 hours.'OIDC_CONFIG_EXPIRATION_TIME':600,}OIDC back channel logout endpointDjango-helusers provides anOIDC back channel logoutendpoint implementation.By default the OIDC back channel logout endpoint is disabled. You can enable it in your project's settings:# myproject/settings.pyHELUSERS_BACK_CHANNEL_LOGOUT_ENABLED=True# These settings specify which authentication server(s) are trusted# to send back channel logout requests.OIDC_API_TOKEN_AUTH={# Who we trust to sign the logout tokens. The library will request# the public signature keys from standard locations below this URL.# Multiple issuers are supported, so this setting can also be a list# of strings. Default is https://tunnistamo.hel.fi.'ISSUER':'https://api.hel.fi/sso/openid'# Audience that must be present in the logout token for it to# be accepted. Value must be agreed between your SSO service# and your application instance. Essentially this allows your# application to know that the token is meant to be used with# it. Multiple acceptable audiences are supported, so this# setting can also be a list of strings. This setting is required.'AUDIENCE':'https://api.hel.fi/auth/projects',}You will also need to add Django-helusers URLs to your URL dispatcher configuration:# myproject/urls.pyurlpatterns=[...# You can adjust the prefix as you wantpath('helauth/',include('helusers.urls')),...]With these settings your project now provides an endpoint athttps://<your-domain>/helauth/logout/oidc/backchannel/that responds to the OIDC back channel logout requests.When the endpoint receives a valid request, it stores information about the logout event to the database. This information is used when authentication for other requests is performed. Thehelusers.oidc.RequestJWTAuthenticationclass that performs authentication based on a JWT bearer token, checks if the token's session has been terminated (by a logout event), and if that's the case, it doesn't authenticate the caller.Logout event callbackThe project using the OIDC back channel logout functionality has an option to attach a callback into the logout event handler. This is done by telling Django-helusers where this callback is located. Configure it in your project's settings:# myproject/settings.pyHELUSERS_BACK_CHANNEL_LOGOUT_CALLBACK="myproject.utils.logout_callback"When a valid logout event is received, the callback is called. The callback receives two keyword arguments:request: theHttpRequestobject describing the request to the logout endpointjwt: ahelusers.jwt.JWTinstance of the logout tokenThe callback can affect the result of the back channel logout event handling by returning anHttpResponseinstance with a status code between 400 and 599 inclusive. If such a response object is returned by the callback, the logout event handling is terminated and the response is sent to the requester. Any other kind of return value from the callback is ignored.Adding Tunnistamo authenticationdjango-helusers ships with backend for authenticating against Tunnistamo
using OIDC. Configuring this includes a Tunnistamo login button to the admin login screen.There is also a deprecated legacy OAuth2 backend using
allauth framework.Includesocial-auth-app-djangoin your project's dependencies.Addsocial_djangointo yourINSTALLED_APPSsetting:# myproject/settings.pyINSTALLED_APPS=(...'social_django',...)Typically you would want to support authenticating using both OIDC and local
database tables. Local users are useful for initial django admin login, before
you've delegated permissions to users coming through OIDC.Add backend configuration to yoursettings.py:AUTHENTICATION_BACKENDS=['helusers.tunnistamo_oidc.TunnistamoOIDCAuth','django.contrib.auth.backends.ModelBackend',]LOGIN_REDIRECT_URL='/'LOGOUT_REDIRECT_URL='/'LOGIN_REDIRECT_URLis the default landing URL after succesful login, if your
form did not specify anything else.LOGOUT_REDIRECT_URLis the same for logout. django-helusers requires this
to be set.You will also need to add URLs forsocial_django&helusersto your URL
dispatcher configuration (urls.py):urlpatterns=[...path('pysocial/',include('social_django.urls',namespace='social')),path('helauth/',include('helusers.urls')),...]You can change the paths if they conflict with your application.Finally, you will need to configure your SESSION_SERIALIZER. helusers stores
the access token expiration time as a datetime which is not serializable
to JSON, so Django needs to be configured to use the built-in
PickleSerializer:SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'Django session loginDjango session login is the usual login to Django that sets up a session
and is typically implemented using a browser cookie. This is usually done
using form with username & password fields. Django-helusers adds another
path that delegates the login to an OIDC provider. User logs in at the
provider and, upon successful return, a Django session is created for them.
For us, the main use case has been allowing logins to Django admin.To support session login Django-helusers needs three settings that must
be configured both at Helsinki OIDC provider and your project instance.
The settings are:client IDclient secretTunnistamo OIDC endpointClientis OAuth2 / OIDC name for anything wanting to authenticate
users. Thus your application would be aclientAdditionally you will need to provide your "callback URL" to the folks
configuring Tunnistamo. This is implemented bypython-social-authand
will, by default, behttps://app.domain/auth/complete/tunnistamo/. During
development on your own laptop yourapp.domainwould belocalhost.After you've received your client ID, client secret and Tunnistamo OIDC
endpoint you would configure them as follows:SOCIAL_AUTH_TUNNISTAMO_KEY='https://i/am/clientid/in/url/style'SOCIAL_AUTH_TUNNISTAMO_SECRET='iamyoursecret'SOCIAL_AUTH_TUNNISTAMO_OIDC_ENDPOINT='https://tunnistamo.example.com/'Note thatclient IDbecomesKEYandclient secretbecomesSECRET.Active Directory groupsHelusers can sync users AD groups to local Django groups when using an AD
login method in Tunnistamo. To enable groups sync you should add "ad_groups"
scope to the Tunnistamo OIDC authorize call. It can be done by adding
the following to the settings:SOCIAL_AUTH_TUNNISTAMO_SCOPE='ad_groups'That setting will add "ad_groups" scope to the default social auth scopes
"openid profile email". If you would like to modify the default social
auth scopes you can set all of the scopes in theSOCIAL_AUTH_TUNNISTAMO_SCOPEsetting and setSOCIAL_AUTH_TUNNISTAMO_IGNORE_DEFAULT_SCOPEtoTrue.Additionally, the client in Tunnistamo should be configured with AD groups
enabled.When the users returns from Tunnistamo with "ad_groups" claim set Helusers will
add all of the groups as an instance ofADGroupmodel to the database.Then, Helusers will add any missing ADGroups to the users' ad_groups-relation
and remove any ADGroups the user is not a member of anymore.To use groups in Django permissions, you should use the Django admin view
(HELSINKI USERS > AD Group Mappings) to set mappings between ADGroups and
Groups. Helusers will then add the user to Django groups that are mapped
to their AD Groups.Note that after creating mappings you cannot manually add a user to a mapped
group if they are not a member of the corresponding AD group because the
group will be removed the next time the user logs in.Adding tunnistamo URL to template contextIf you need to access the Tunnistamo API from your JS code, you can include
the Tunnistamo base URL in your template context using helusers's context processor:TEMPLATES=[{'OPTIONS':{'context_processors':['helusers.context_processors.settings']}}]Carrying language preference from your application to TunnistamoTunnistamo (per the OIDC specs) allows clients to specify the language used for
the login process. This allows you to carry your applications language setting
to the login screens presented by Tunnistamo.Configurepython-social-authto pass the necessary argument through its
login view:SOCIAL_AUTH_TUNNISTAMO_AUTH_EXTRA_ARGUMENTS={'ui_locales':'fi'}fithere is the language code that will be used when no language is requested, so change it if you you prefer some
other default language. If you don't want to set a default language at all, use an empty string""as the language
code.When this setting is in place, languages can be requested using query paramui_locales=<language code>when starting
the login process, for example in your template<a href="{% url 'helusers:auth_login' %}?next=/foobar/&ui_locales=en">Login in English</a>Disabling password loginsIf you're not allowing users to log in with passwords, you may disable the
username/password form from Django admin login page by settingHELUSERS_PASSWORD_LOGIN_DISABLEDtoTrue.DevelopmentVirtual Python environment can be used. For example:python3-mvenv.venvsource.venv/bin/activateInstall package requirements:pipinstall-e.Install development requirements:pipinstallpip-tools
pip-compilerequirements-dev.in
pipinstall-rrequirements-dev.txtRunning testspytest