Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • anlambert/swh-auth
  • franckbret/swh-auth
  • lunar/swh-auth
  • swh/devel/swh-auth
  • douardda/swh-auth
  • marmoute/swh-auth
  • Alphare/swh-auth
7 results
Show changes
Commits on Source (111)
# Changes here will be overwritten by Copier
_commit: v0.3.3
_src_path: https://gitlab.softwareheritage.org/swh/devel/swh-py-template.git
description: Software Heritage authentication utilities
distribution_name: swh-auth
have_cli: true
have_workers: false
package_root: swh/auth
project_name: swh.auth
python_minimal_version: '3.7'
readme_format: rst
# python: Reformat code with black
a30d9355cdd906eb4045eabfac921e6d665c4c98
b7bb1b6add4358cfa271da64516e489f4c2afa56
*.egg-info/
*.pyc
.coverage
.eggs/
.hypothesis
.mypy_cache
.tox
__pycache__
build/
dist/
# these are symlinks created by a hook in swh-docs' main sphinx conf.py
docs/README.rst
docs/README.md
# this should be a symlink for people who want to build the sphinx doc
# without using tox, generally created by the swh-env/bin/update script
docs/Makefile.sphinx
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: check-json
- id: check-yaml
- repo: https://github.com/python/black
rev: 25.1.0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 6.0.0
hooks:
- id: isort
- repo: https://github.com/pycqa/flake8
rev: 7.1.1
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear==24.12.12, flake8-pyproject]
- repo: https://github.com/codespell-project/codespell
rev: v2.4.1
hooks:
- id: codespell
name: Check source code spelling
stages: [pre-commit]
- id: codespell
name: Check commit message spelling
stages: [commit-msg]
- repo: local
hooks:
- id: mypy
name: mypy
entry: mypy
args: [swh]
pass_filenames: false
language: system
types: [python]
- id: twine-check
name: twine check
description: call twine check when pushing an annotated release tag
entry: bash -c "ref=$(git describe) &&
[[ $ref =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] &&
(python3 -m build --sdist && twine check $(ls -t dist/* | head -1)) || true"
pass_filenames: false
stages: [pre-push]
language: python
additional_dependencies: [twine, build]
Copyright (C) 2019 The Software Heritage developers
See http://www.softwareheritage.org/ for more information.
# Software Heritage Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as Software
Heritage contributors and maintainers pledge to making participation in our
project and our community a harassment-free experience for everyone, regardless
of age, body size, disability, ethnicity, sex characteristics, gender identity
and expression, level of experience, education, socioeconomic status,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at `conduct@softwareheritage.org`. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an
incident. Further details of specific enforcement policies may be posted
separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
This diff is collapsed.
# Makefile driver for SWH Python modules. DO NOT CHANGE.
# You can add custom Makefile rules to Makefile.local
include ../Makefile.python
-include Makefile.local
Software Heritage - Authentication
==================================
``swh-auth`` is a set of utility libraries related to user authentication
in applications and services based on the use of `Keycloak`_ and `OpenID Connect`_.
`Keycloak`_ is an open source software enabling single sign-on (SSO) with identity
and access management.
`OpenID Connect`_ (OIDC) is an authentication layer on top of `OAuth 2.0`_, widely
used in modern web applications and services.
``swh-auth`` notably offers the following features:
- the ``swh.auth.keycloak.KeycloakOpenIDConnect`` class to ease the
interaction with a Keycloak server
- a ``pytest`` plugin with the ``keycloak_oidc`` fixture to mock Keycloak
responses in unit tests
- generic backends, views and middlewares to easily plug OpenID Connect authentication
in any `Django`_ or `Django REST framework`_ application
.. _Keycloak: https://www.keycloak.org/
.. _OpenID Connect: https://openid.net/connect/
.. _OAuth 2.0: https://oauth.net/2/
.. _Django: https://www.djangoproject.com/
.. _Django REST framework: https://www.django-rest-framework.org/
\ No newline at end of file
# Copyright (C) 2021 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
pytest_plugins = ["swh.auth.pytest_plugin"]
_build/
apidoc/
*-stamp
include Makefile.sphinx
../README.rst
\ No newline at end of file
.. _swh-auth-cli:
Command-line interface
======================
.. click:: swh.auth.cli:auth
:prog: swh auth
:nested: full
from swh.docs.sphinx.conf import * # NoQA
Django components
=================
``swh-auth`` implements some generic backends, models, views and middlewares
to easily authenticate a user with Keycloak and OpenID Connect.
OIDC User model
---------------
When ``swh-auth`` authenticates users with OIDC in a Django application,
it creates an instance of the :class:`swh.auth.django.models.OIDCUser`
model and attaches it to the input ``django.http.HttpRequest`` object.
That model acts as a proxy for the ``django.contrib.auth.models.User`` model
and is not persisted to database as user information is already stored
in Keycloak database. As a consequence it will not be considered when calling
the ``makemigrations`` command from Django application management CLI.
Authentication backends
-----------------------
``swh-auth`` provides two authentication backends to login users in
Django applications:
- :class:`swh.auth.django.backends.OIDCAuthorizationCodePKCEBackend`: authenticate
users from a Web application UI
- :class:`swh.auth.django.backends.OIDCBearerTokenAuthentication`: authenticate
REST API users from bearer tokens sent in HTTP Authorization headers.
These backends need to be configured through the following Django settings:
- ``SWH_AUTH_SERVER_URL``: Base URL of the Keycloak server to interact with
- ``SWH_AUTH_REALM_NAME``: Name of the realm to use in the Keycloak instance
- ``SWH_AUTH_CLIENT_ID``: Name of the client to use in the realm
.. warning::
These backends internally use the Django cache to store authenticated user data.
In production environment, it is important to ensure the cache will be shared
across the multiple WSGI workers (by using Django memcached cache backend
for instance).
Authorization Code flow with PKCE backend
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This backend can be used to authenticate users with the OpenID Connect Authorization
Code flow with PKCE (`Proof Key for Code Exchange`_).
PKCE replaces the static secret used in the standard authorization code flow with a
temporary one-time challenge, making it feasible to use in public clients.
When using that backend, users are redirected to the Keycloak login UI and are
asked to enter their credentials. Once successfully authenticated, users will
be redirected back to the Django application.
To use that backend, add ``"swh.auth.django.backends.OIDCAuthorizationCodePKCEBackend"``
to the ``AUTHENTICATION_BACKENDS`` Django setting.
The backend must be used in collaboration with the dedicated :ref:`login-logout-views`
implementing the authentication flow.
Bearer token backend
^^^^^^^^^^^^^^^^^^^^
This backend for Django REST Framework enables to authenticate Web API users by sending
long-lived OpenID Connect refresh tokens in HTTP Authorization headers.
Long lived refresh tokens can be generated in Keycloak by opening an OpenID Connect
session with the following scope: ``openid offline_access``.
To use that backend, add ``"swh.auth.django.backends.OIDCBearerTokenAuthentication"``
to the ``REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]`` Django setting.
Users can then perform authenticated Web API calls by sending their refresh token
in HTTP Authorization headers, for instance when using ``curl``::
curl -H "Authorization: Bearer ${TOKEN}" https://....
.. _login-logout-views:
Login / logout views
--------------------
In order to login / logout a user with OIDC Authorization code flow with PKCE, two
dedicated Django views are available in ``swh-auth``:
- ``oidc-login`` (``/oidc/login/`` URL path): initiate authentication flow
- ``oidc-logout`` (``/oidc/logout/`` URL path): terminate OIDC user session, a ``next``
query parameter can be used to redirect to a view of choice once a user is logged out
Add ``swh.auth.django.views.urlpatterns`` to your Django application URLs to use them.
Middlewares
-----------
``swh-auth`` provides the :class:`swh.auth.django.middlewares.OIDCSessionExpiredMiddleware`
middleware.
That middleware detects when a user previously logged in using the OpenID Connect
authentication backend got his session expired.
In that case it redirects to a Django view whose name is set in the
``SWH_AUTH_SESSION_EXPIRED_REDIRECT_VIEW`` Django setting (typically a logout view).
The following query parameter will be set for that view:
- ``next``: requested URL before the detection of the OIDC session expiration
- ``remote_user``: indicates that the user was previously authenticated with OIDC
Minimal application example
---------------------------
A sample minimal Django application using all the features mentioned above can be
found in `swh-auth Django tests tree`_.
.. _Proof Key for Code Exchange: https://tools.ietf.org/html/rfc7636
.. _swh-auth Django tests tree: https://forge.softwareheritage.org/source/swh-auth/browse/master/swh/auth/tests/django/app/apptest/
.. _swh-auth:
.. include:: README.rst
Reference Documentation
-----------------------
.. toctree::
:maxdepth: 2
cli
django
.. only:: standalone_package_doc
Indices and tables
------------------
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`