2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-06-14 11:05:41 +00:00

feat(backend): add oauth2 (#9333)

* feat(backend): add oauth2

* fix import

* Add inventree roles

* refactor to make lookup more efficient

* fix single scope definitions

* cleanup

* fix schema

* reduce auth methods

* fix OAuth validator

* re-enable token and basic auth again

* Add models to role mapping

* change scope args

* add debug step for schema generation

* add oauth config for schema generation

* improve token -> permission mapping

* fix req

* extend checks to ensure normal auth also passes

* fix api version

* fix ignore

* fix rule name

* bump api version

* remove old modelref

* move scope definition

* make test results easier to work with

* add tests to ensure scopes are in sync with rulesets

* fix docstring

* fix various permissions and their mapping to oauth

* refactor

* simplify

* fix permission mapping

* ignore failure cases

* fix unauthenticated access

* flag oAuth2 till it is done

* Add OIDC support

* add RSA key generation and docs

* fix test

* move imports

* update ignore

* feat(backend): Add API Schema stats

* add scope stats

* fix name

* fix scope output

* feat(backend): test custom command

* add warning for unknown scopes

* reduce diff in launch.json

* cleanup  diff

* add error code for ruleset / scope issues

* update structure

* add oauth docs

* add experimetnal feature docs

* simplify metadata endpoint

* add importer model

* refactor(backend): simplify metadata endpoint

* fix imports

* simplify even more

* remove unneeded schema tooling

* fix permission mappings

* fix testing

* fix role calculations

* fix mapping

* remove importer change to unblock this

* remove importer scope everywhere

* fix merge conflict in test

* add missing models

* fix api version

* fix OASToken matcher

* revert permission class change

* reduce size of test log by writing schema

* fix permissions

* fix file path

* extend schema to remove need for TokenMatchesOASRequirements

* cleanup permissions file

* add base object permission
This commit is contained in:
Matthias Mair
2025-04-18 11:27:32 +02:00
committed by GitHub
parent afbcfe66bb
commit 8bb03b7afd
43 changed files with 718 additions and 204 deletions

View File

@ -33,7 +33,7 @@ invoke dev.schema -help
Users must be authenticated to gain access to the InvenTree API. The API accepts either basic username:password authentication, or token authentication. Token authentication is recommended as it provides much faster API access.
!!! warning "Permissions"
API access is restricted based on the permissions assigned to the user.
API access is restricted based on the permissions assigned to the user or scope of the application.
### Basic Auth
@ -44,9 +44,9 @@ Users can authenticate against the API using basic authentication - specifically
Each user is assigned an authentication token which can be used to access the API. This token is persistent for that user (unless invalidated by an administrator) and can be used across multiple sessions.
!!! info "Token Administration"
User tokens can be created and/or invalidated via the Admin interface.
User tokens can be created and/or invalidated via the user settings, admin center or admin interface.
### Requesting a Token
#### Requesting a Token
If a user does not know their access token, it can be requested via the API interface itself, using a basic authentication request.
@ -66,7 +66,7 @@ HTTP_200_OK
}
```
### Using a Token
#### Using a Token
After reception of a valid authentication token, it can be subsequently used to perform token-based authentication.
@ -95,6 +95,46 @@ headers = {
response = request.get('http://localhost:8080/api/part/', data=data, headers=headers)
```
### oAuth2 / OIDC
!!! warning "Experimental"
This is an experimental feature that needs to be specifically enabled. See [Experimental features](../settings/experimental.md) for more information.
InvenTree has built-in support for using [oAuth2](https://oauth.net/2/) and OpenID Connect (OIDC) for authentication to the API. This enables using the instance as a very limited identity provider.
A default application using a public client with PKCE enabled ships with each instance. Intended to be used with the python api and configured with very wide scopes this can also be used for quick tests - the cliend_id is `zDFnsiRheJIOKNx6aCQ0quBxECg1QBHtVFDPloJ6`.
#### Managing applications
Superusers can register new applications and manage existing ones using a small application under the subpath `/o/applications/`.
It is recommended to:
- read the spec (RFC 6749 / 6750) and/or best practices (RFC 9700) before choosing client types
- chose scopes as narrow as possible
- configure redirection URIs as exact as possible
#### Scopes
InvenTree's oAuth scopes are strongly related to the [user roles](#user-roles).
Names consist of 1. type, 2. kind and 3. (opt) role, separated by colons.
There are 3 types:
- a: administrative scopes - used for administrating the server - these can be staff or superuser scopes
- g: general scopes - give wide access to the basic building blocks of InvenTree
- r: role scopes - map to specific actions (2) and roles (3)
Examples:
```bash
a:superuser
g:read
r:change:part
r:delete:stock
```
!!! info "Read the API docs"
The API [documentation](#documentation) and [schema](./schema.md) list the required scopes for every API endpoint / interaction in the security sections.
## Authorization
### User Roles

View File

@ -32,6 +32,18 @@ As the `django.db.models.QuerySet` is not a generic class, we would loose type i
Models that implement the `InvenTreeReportMixin` must have an explicit return type annotation for the `report_context` function.
#### INVE-E5
**Rulesets have issues - Backend**
The rulesets used for managing user/group/oAuth permissions have an issue.
This might be caused by an addition or removal of models to the code base. Running the test suit should surface more logs with the error code indicating the exact infractions.
#### INVE-E6
**Scopes have issues - Backend**
The scopes used for oAuth permissions have an issue and do not match the rulesets.
This might be caused by an addition or removal of models to the code base or changes to the rulesets. Running the test suit should surface more logs with the error code indicating the exact infractions.
### INVE-W (InvenTree Warning)
Warnings - These are non-critical errors which should be addressed when possible.

View File

@ -0,0 +1,17 @@
---
title: Experimental Features
---
## Feature Flags
InvenTree ships with django-flags and enables path (parameter), user, session, date or settings based feature flags. This allows admins to slowly test and roll out new features on their instance without running parallel instances.
Additional flags can be provided via the the `INVENTREE_FLAGS` environment key (see [configuration](../start/config.md#environment-variables)).
Superusers can configure run-time conditions [as per django-flags](https://cfpb.github.io/django-flags/conditions/) docs under `/admin/flags/flagstate/`.
## Current Experimental Features
| Feature | Key | Description |
| ------- | ----------- |
| oAuth provider / api | OIDC | Use oAuth and OIDC to authenticate users with the API - [read more](../api/api.md#oauth2--oidc). |

View File

@ -218,31 +218,35 @@ You can either specify the password directly using `INVENTREE_ADMIN_PASSWORD`, o
!!! info "Administrator Account"
Providing `INVENTREE_ADMIN` credentials will result in the provided account being created with *superuser* permissions when InvenTree is started.
## Secret Key
## Secret Key material
InvenTree requires a secret key for providing cryptographic signing - this should be a secret (and unpredictable) value.
InvenTree requires secret keys for providing cryptographic signing and oidc private keys- this should be a secret (and unpredictable) value.
!!! info "Auto-Generated Key"
If none of the following options are specified, InvenTree will automatically generate a secret key file (stored in `secret_key.txt`) on first run.
!!! info "Auto-Generated material"
If none of the following options are specified, InvenTree will automatically generate a secret key file (stored in `secret_key.txt`) and a oidc key file (stored in `oidc.pem`) on first run.
The secret key can be provided in multiple ways, with the following (descending) priorities:
The secret key material can be provided in multiple ways, with the following (descending) priorities:
**Pass Secret Key via Environment Variable**
**Pass Secret Key Material via Environment Variable**
A secret key string can be passed directly using the environment variable `INVENTREE_SECRET_KEY`
A oidc private key can be passed directly using the environment variable `INVENTREE_OIDC_PRIVATE_KEY`
**Pass Secret Key File via Environment Variable**
**Pass Secret Key Material File via Environment Variable**
A file containing the secret key can be passed via the environment variable `INVENTREE_SECRET_KEY_FILE`
A PEM-encoded file containing the oidc private key can be passed via the environment variable `INVENTREE_OIDC_PRIVATE_KEY_FILE`
**Fallback to Default Secret Key File**
**Fallback to Default Secret Key Material**
If not specified via environment variables, the fallback secret_key file (automatically generated as part of InvenTree installation) will be used.
If not specified via environment variables, the fallback files (automatically generated as part of InvenTree installation) will be used.
| Environment Variable | Configuration File | Description | Default |
| --- | --- | --- | --- |
| INVENTREE_SECRET_KEY | secret_key | Raw secret key value | *Not specified* |
| INVENTREE_SECRET_KEY_FILE | secret_key_file | File containing secret key value | *Not specified* |
| INVENTREE_OIDC_PRIVATE_KEY | oidc_private_key | Raw private key value | *Not specified* |
| INVENTREE_OIDC_PRIVATE_KEY_FILE | oidc_private_key_file | File containing private key value in PEM format | *Not specified* |
## Database Options

View File

@ -161,6 +161,7 @@ nav:
- Single Sign on: settings/SSO.md
- Multi Factor Authentication: settings/MFA.md
- Email: settings/email.md
- Experimental Features: settings/experimental.md
- Export Data: settings/export.md
- Import Data: settings/import.md
- Operations: