Skip to main content
DRF And React By Schema - OAuth

DRF And React By Schema - OAuth

OAuth 2.1 authorization server + resource server for projects built with DRF And React By Schema (DRBS).

It turns any DRBS Django/DRF project into a standard OAuth 2.1 provider — with PKCE and Dynamic Client Registration (RFC 7591) — so MCP clients such as opencode (and, later, the SPA/mobile app) can authenticate through a server-rendered Django login/consent page, with no React changes.

About the suite

drf-react-by-schema is a suite that builds headless Django + React applications directly from your models:

  • drf-react-by-schema-django (PyPI) — generates the DRF API (serializers, viewsets, filters, schemas) from your models;

  • drf-react-by-schema-react (npm) — consumes those schemas to build the React forms, grids and CRUD interfaces;

  • drf-react-by-schema-oauth (this package) — adds the authorization layer so clients can obtain and use OAuth 2.1 tokens against the same API;

  • drf-react-by-schema-mcp — a generic, schema-driven MCP server that exposes a DRBS project to MCP clients, authorized by this package’s tokens.

About this package

DRBS projects expose a rich DRF API generated from the Django models. This package adds the missing authorization layer on top of django-oauth-toolkit (DOT):

  • an OAuth 2.1 authorization server (authorization code + PKCE S256, refresh token);

  • Dynamic Client Registration (RFC 7591) so opencode mcp auth <sistema> works with no manual client setup;

  • Authorization Server Metadata (RFC 8414) and a helper to build Protected Resource Metadata (RFC 9728; served by the MCP package);

  • a DRF authentication class and read/write scope permissions that authenticate both /mcp and /api/... with the same Bearer token;

  • per-user service tokens — helpers to mint/reuse/revoke a server-side Bearer credential carrying a user’s identity and scope, for trusted server-side components (see “Service tokens”);

  • server-rendered login/consent templates that projects can override.

It is additive and opt-in: it does not replace Django auth or SimpleJWT, and requires no SPA work.

Compatibility

The base DRBS package supports Django ≥ 3.2, and some deployments are still on Django 3.2. Newer django-oauth-toolkit (3.x) requires Django ≥ 4.2, so this package pins the 2.x DOT line (django-oauth-toolkit>=2.4,<3.0), which supports Django 3.2 through 5.x. (The suite’s roadmap is to move consumer apps to Django 5, at which point the DOT pin can be relaxed.)

Pre-requisites

  • Django ≥ 3.2

  • djangorestframework

  • django-oauth-toolkit (2.x, installed automatically)

Quick start

  1. Install:

    pip install drf-react-by-schema-oauth
  2. Add the DOT app and this package to INSTALLED_APPS (order matters — oauth2_provider first):

    INSTALLED_APPS = [
        ...
        'oauth2_provider',
        'drf_react_by_schema_oauth',
    ]
  3. Include the URLs:

    from django.urls import include, path
    
    urlpatterns = [
        ...
        path('', include('drf_react_by_schema_oauth.urls')),
    ]
  4. Migrate (creates DOT’s token/application tables):

    python manage.py migrate

That is the whole consumer contract: two apps, one include(), one migrate.

Accepting OAuth tokens on your API

To let the same Bearer token authenticate /api/... (used by the SPA via JWT and by MCP via OAuth), add the authentication class to your DRF settings or per viewset:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # OAuth *first*: SimpleJWT raises AuthenticationFailed on a non-JWT
        # Bearer (e.g. an OAuth access token) and would stop the chain before
        # OAuth is tried. OAuth2Authentication returns None (not an error) for
        # non-OAuth tokens, so JWT/session still resolve afterwards.
        'drf_react_by_schema_oauth.authentication.OAuth2Authentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    ...
}

Then add HasScope where you want OAuth tokens to be scope-limited (e.g. a read-only token cannot write). It is composable: requests authenticated by session/JWT are left to your own permissions, only OAuth tokens are scope-checked.

from rest_framework.permissions import IsAuthenticated
from drf_react_by_schema_oauth.permissions import HasScope

class MyViewSet(viewsets.ModelViewSet):
    authentication_classes = [
        OAuth2Authentication,   # first, for the reason above
        JWTAuthentication,
        SessionAuthentication,
    ]
    permission_classes = [IsAuthenticated, HasScope]

A view can demand an explicit set instead of the default method mapping:

class ReportView(APIView):
    required_scopes = ['read']
    permission_classes = [IsAuthenticated, HasScope]

Settings

All settings live in a single optional DRBS_OAUTH dict:

DRBS_OAUTH = {
    # Canonical public base URL of the authorization server (RFC 8414
    # `issuer`). Set it in production; when unset it is derived from the
    # request origin.
    'ISSUER': 'https://auth.example.org',

    # Scopes advertised, accepted and shown on the consent page (name ->
    # description). This is the single source of truth: the package feeds
    # these into DOT's consent rendering, so you do not need to duplicate
    # them in OAUTH2_PROVIDER['SCOPES'].
    'SCOPES': {
        'read': 'Read access to the API.',
        'write': 'Write access to the API.',
    },

    # Dynamic Client Registration.
    'DCR_ENABLED': True,
    'DCR_ALLOWED_REDIRECTS': [  # scheme+host prefixes; loopback by default
        'http://127.0.0.1',
        'http://localhost',
        'http://[::1]',
    ],

    # Optional template overrides (see "Templates" below).
    'LOGIN_TEMPLATE': None,     # defaults to "drbs_oauth/login.html"
    'CONSENT_TEMPLATE': None,   # defaults to "drbs_oauth/authorize.html"

    # Per-user service tokens (see "Service tokens" below). One confidential
    # client-credentials application represents every service token; the
    # helpers mint/reuse/revoke access tokens under it.
    'SERVICE_TOKENS': {
        'ENABLED': True,            # informational flag for consumers
        'APPLICATION_NAME': 'DRBS Agent Console',
        'SCOPE': 'read',            # read-only by design
        'LIFETIME': timedelta(days=30),   # from datetime import timedelta
    },

    # Reserved.
    'AUDIENCE': None,
    'ACCESS_TOKEN_TTL': None,
    'REFRESH_TOKEN_TTL': None,
}

Endpoints

  • /.well-known/oauth-authorization-server — Authorization Server Metadata (RFC 8414)

  • /o/authorize/ — authorization endpoint (login + consent)

  • /o/token/ — token endpoint

  • /o/revoke_token/ — token revocation (RFC 7009)

  • /o/introspect/ — token introspection (RFC 7662)

  • /o/register/ — Dynamic Client Registration (RFC 7591)

  • /o/login/ — server-rendered login page

Scopes

Two scopes are defined and advertised:

  • read — safe methods (GET/HEAD/OPTIONS/TRACE);

  • write — unsafe methods (POST/PUT/PATCH/DELETE).

The names are also exported as constants (drf_react_by_schema_oauth.SCOPE_READ / SCOPE_WRITE).

Templates

The login and consent pages are plain server-rendered HTML and require no build step. Override them either by pointing DRBS_OAUTH at your own template names (LOGIN_TEMPLATE / CONSENT_TEMPLATE) or by shadowing drbs_oauth/login.html / drbs_oauth/authorize.html from a project template directory.

Using with MCP (opencode)

Once a project is deployed with this package (and the MCP package mounts /mcp), an opencode user authorizes with:

opencode mcp auth <sistema>

opencode:

  1. discovers the authorization server (via the resource server’s Protected Resource Metadata and/or /.well-known/oauth-authorization-server);

  2. registers a client dynamically at /o/register/;

  3. opens the Django-rendered login/consent page in the browser;

  4. stores a per-user access/refresh token and calls /mcp with it.

No credential is ever centralized: each system authorizes its own users and keeps Django as the permission authority.

Service tokens (per-user credentials)

Besides the interactive OAuth flow, a project can provision a per-user service token: a server-side Authorization: Bearer credential that carries a Django user’s identity and a fixed scope. It is meant for trusted server-side components (for example an Agent Console running one opencode process per logged-in user), so their calls to /mcp — and, through it, /api/... — are scoped by the API’s own DRF permissions.

from drf_react_by_schema_oauth import (
    get_or_create_application,
    get_or_mint_token,
    revoke_tokens,
)

application = get_or_create_application()   # one confidential client
token = get_or_mint_token(user)             # reuse an unexpired token…
# …or a fresh one, with an explicit scope/lifetime:
token = get_or_mint_token(user, scope='write', lifetime=timedelta(hours=1))
revoked = revoke_tokens(user)               # -> number of tokens deleted
  • get_or_create_application(name=None, owner=None) returns — creating it once — the single confidential, client-credentials Application that backs every service token; name defaults to SERVICE_TOKENS['APPLICATION_NAME'].

  • get_or_mint_token(user, *, scope=None, lifetime=None) returns a live token for user and scope, reusing an unexpired one so repeated provisioning is idempotent; scope/lifetime default to the settings block.

  • revoke_tokens(user, *, scope=None) deletes the matching service tokens and returns how many were removed.

A service token is a credential: inject it into the server-side process and never send it to the browser. The helpers import django-oauth-toolkit’s models lazily, so importing the package never touches the token tables. SERVICE_TOKENS['ENABLED'] is an informational flag for the consumer — the helpers themselves do not gate on it.

Security notes

  • Dynamic client registration creates public clients only (no client secret), and redirect URIs are restricted to loopback by default (RFC 8252); plain http is allowed only for loopback hosts.

  • Access and refresh tokens are stored by DOT as its own hashed records — this package introduces no additional secret store.

  • Set DRBS_OAUTH['ISSUER'] in production so the advertised issuer does not depend on the incoming Host header.

  • Introspection is protected by DOT and requires a Bearer token carrying the introspection scope.

License

GNU Affero General Public License v3.0 or later — see LICENSE.

Metadata

Release files for drf-react-by-schema-oauth 0.2.0

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

Source distribution (sdist)

Source distribution for drf-react-by-schema-oauth 0.2.0
File Size Uploaded Provenance Actions
drf_react_by_schema_oauth-0.2.0.tar.gz 600.3 kB With provenance Details for drf_react_by_schema_oauth-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drf-react-by-schema-oauth 0.2.0
File Interpreter ABI Platform Actions
drf_react_by_schema_oauth-0.2.0-py3-none-any.whl Python 3 none any Details for drf_react_by_schema_oauth-0.2.0-py3-none-any.whl

Total release size: 646.9 kB

Release files / drf_react_by_schema_oauth-0.2.0.tar.gz

Download URL drf_react_by_schema_oauth-0.2.0.tar.gz
Size 600.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c9df6d6fe64db6f6a402fd1922bfba071985b9793f59f795db233e454dc06e2a
BLAKE2b-256 checksum
How to use checksums
e6c56542dd5e25e0c83569f1545eaad057a7d02feade53b2b473c0f7e46f879b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitLab CI/CD, verified by PyPI on Nov 11, 2026.

Transparency log

Release files / drf_react_by_schema_oauth-0.2.0-py3-none-any.whl

Download URL drf_react_by_schema_oauth-0.2.0-py3-none-any.whl
Size 46.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aeb9b831a175b43f593800aff71dbe299dd1474378d2b6e2cbbab6346076dcab
BLAKE2b-256 checksum
How to use checksums
65c7d4e45f500c2281810f0ebb3f99ab2736e3033d6069f6c7d7e68f126bcd96
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.12.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitLab CI/CD, verified by PyPI on Nov 11, 2026.

Transparency log

Security for drf-react-by-schema-oauth 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for drf_react_by_schema_oauth-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitLab CI/CD, verified by PyPI on Nov 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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