/api` | The default `aud`, used when a request names no `resource`. |
+| `OAUTH_RESOURCES` | `[]` | Further resource identifiers (RFC 8707) a client may request. The default audience is always allowed. |
| `OAUTH_ACCESS_TOKEN_TTL` | 300 s | |
| `OAUTH_REFRESH_TOKEN_TTL` / `OAUTH_REFRESH_FAMILY_TTL` | 14 / 30 days | Per token, and the absolute lifetime of a grant. |
| `OAUTH_DPOP_ALGORITHMS` | ES256, ES384, Ed25519, PS256 | |
@@ -289,8 +295,8 @@ docs/adr/ architecture decision records
discovery beyond RFC 8414.
- **No dynamic client registration** (RFC 7591). Clients are registered with
`manage.py create_client` or the admin.
-- **One audience.** Resource indicators (RFC 8707) are not implemented, so
- every token's `aud` is `OAUTH_ACCESS_TOKEN_AUDIENCE`.
+- **One audience per token.** Resource indicators (RFC 8707) are supported,
+ but a token request names at most one `resource`.
- **DPoP only.** There is no bearer-token fallback and no mTLS (RFC 8705);
see ADR 0005.
- **Consent is not remembered.** Every authorization asks again.
@@ -310,6 +316,10 @@ docs/adr/ architecture decision records
- [`ci-workflows`](https://github.com/CtrlAltDevelop/ci-workflows): the shared
CI this repository calls.
+## Contributing and security
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md). Changes are listed in [CHANGELOG.md](CHANGELOG.md).
+
## License
-[MIT](LICENSE) © 2026 Mohammad Zarif
+[AGPL-3.0-only](LICENSE) © 2026 Mohammad Zarif
diff --git a/authserver/api.py b/authserver/api.py
index 9ac49a4..37c0595 100644
--- a/authserver/api.py
+++ b/authserver/api.py
@@ -63,6 +63,7 @@ def jwks(request: HttpRequest) -> JsonResponse:
"redirect_uri": "authorization_code: the redirect_uri of the authorization request",
"refresh_token": "refresh_token: the current refresh token",
"scope": "refresh_token, client_credentials: optional narrower scope",
+ "resource": "Optional: the one resource server (RFC 8707) the token is for",
"client_id": "public clients, and client_secret_post",
"client_secret": "client_secret_post",
},
@@ -175,6 +176,7 @@ def revocation(request: HttpRequest) -> JsonResponse:
"state": "Opaque value returned with the response",
"code_challenge": "PKCE S256 challenge",
"code_challenge_method": "S256",
+ "resource": "Optional, repeatable: the resource servers (RFC 8707) the grant covers",
"dpop_jkt": "Optional: thumbprint of the key the code will be bound to",
"client_id": "The client",
"client_secret": "client_secret_post",
diff --git a/authserver/authorization.py b/authserver/authorization.py
index 93d56eb..7d47292 100644
--- a/authserver/authorization.py
+++ b/authserver/authorization.py
@@ -7,7 +7,7 @@
to the client by redirect (``AuthorizationError``).
"""
-from dataclasses import asdict, dataclass
+from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from typing import Any
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
@@ -20,6 +20,7 @@
from authserver.credentials import digest, new_token
from authserver.http import single_valued
from authserver.models import AuthorizationCode, Client
+from authserver.resources import known_resources
from authserver.scopes import format_scope, parse_scope
_JKT_LENGTH = 43 # base64url SHA-256, as every RFC 7638 thumbprint here is
@@ -55,6 +56,8 @@ class AuthorizationRequest:
state: str | None
code_challenge: str
dpop_jkt: str | None
+ # RFC 8707. Defaulted so a request stashed before an upgrade still loads.
+ resources: list[str] = field(default_factory=list)
def as_session_data(self) -> dict[str, Any]:
return asdict(self)
@@ -99,6 +102,8 @@ def fail(error: str, reason: str) -> AuthorizationError:
if state is not None and len(state) > _MAX_STATE_LENGTH:
raise fail("invalid_request", "state is too long")
+ # RFC 8707 §2.1: `resource` is the one parameter that may be repeated.
+ repeated = repeated - {"resource"}
if repeated:
raise fail("invalid_request", f"repeated parameters: {sorted(repeated)}")
if params.get("response_type") != "code":
@@ -129,6 +134,11 @@ def fail(error: str, reason: str) -> AuthorizationError:
if dpop_jkt is not None and len(dpop_jkt) != _JKT_LENGTH:
raise fail("invalid_request", "dpop_jkt is malformed")
+ try:
+ resources = known_resources(client, lists.get("resource", []))
+ except ValueError:
+ raise fail("invalid_target", "resource is not registered") from None
+
return AuthorizationRequest(
client_id=client.client_id,
redirect_uri=redirect_uri,
@@ -136,6 +146,7 @@ def fail(error: str, reason: str) -> AuthorizationError:
state=state,
code_challenge=challenge,
dpop_jkt=dpop_jkt,
+ resources=resources,
)
@@ -168,6 +179,7 @@ def issue_code(request: AuthorizationRequest, user: AbstractBaseUser, auth_time:
scope=format_scope(request.scope),
code_challenge=request.code_challenge,
dpop_jkt=request.dpop_jkt or "",
+ resources=request.resources,
auth_time=auth_time,
expires_at=now + timedelta(seconds=server_settings().authorization_code_ttl),
)
diff --git a/authserver/clients.py b/authserver/clients.py
index f56241c..e1dd4a8 100644
--- a/authserver/clients.py
+++ b/authserver/clients.py
@@ -45,6 +45,7 @@ def register_client(
grant_types: list[str],
redirect_uris: list[str],
scopes: list[str],
+ resources: list[str] | None = None,
can_introspect: bool = False,
) -> tuple[Client, str | None]:
"""Create a client, returning it with its plaintext secret (if any).
@@ -69,6 +70,10 @@ def register_client(
if unknown_scopes:
raise ValueError(f"unknown scopes: {sorted(unknown_scopes)}")
+ unknown_resources = set(resources or []) - set(server_settings().resources)
+ if unknown_resources:
+ raise ValueError(f"unregistered resources: {sorted(unknown_resources)}")
+
secret = new_token() if confidential else None
client = Client.objects.create(
client_id=new_token(),
@@ -78,6 +83,7 @@ def register_client(
redirect_uris=list(redirect_uris),
grant_types=list(dict.fromkeys(grant_types)),
scopes=list(dict.fromkeys(scopes)),
+ resources=list(dict.fromkeys(resources or [])),
can_introspect=can_introspect,
)
return client, secret
diff --git a/authserver/conf.py b/authserver/conf.py
index 7e880d1..e27a5d4 100644
--- a/authserver/conf.py
+++ b/authserver/conf.py
@@ -27,6 +27,7 @@
class ServerSettings:
issuer: str
audience: str
+ resources: tuple[str, ...]
scopes: dict[str, str]
access_token_ttl: int
authorization_code_ttl: int
@@ -55,9 +56,13 @@ def _get(name: str, default: Any) -> Any:
def server_settings() -> ServerSettings:
issuer = str(_get("OAUTH_ISSUER", "http://localhost:8000")).rstrip("/")
access_token_ttl = int(_get("OAUTH_ACCESS_TOKEN_TTL", 300))
+ audience = str(_get("OAUTH_ACCESS_TOKEN_AUDIENCE", f"{issuer}/api"))
return ServerSettings(
issuer=issuer,
- audience=str(_get("OAUTH_ACCESS_TOKEN_AUDIENCE", f"{issuer}/api")),
+ audience=audience,
+ # RFC 8707: the resource servers a client may ask a token for. The
+ # default audience is always one, so existing clients keep working.
+ resources=tuple(dict.fromkeys([audience, *_get("OAUTH_RESOURCES", [])])),
scopes=dict(_get("OAUTH_SCOPES", DEFAULT_SCOPES)),
access_token_ttl=access_token_ttl,
authorization_code_ttl=int(_get("OAUTH_AUTHORIZATION_CODE_TTL", 60)),
diff --git a/authserver/errors.py b/authserver/errors.py
index c917313..e75edf9 100644
--- a/authserver/errors.py
+++ b/authserver/errors.py
@@ -22,6 +22,7 @@
"unsupported_grant_type": "The grant type is not supported.",
"unsupported_response_type": "The response type is not supported.",
"invalid_scope": "The requested scope is invalid or exceeds what the client may request.",
+ "invalid_target": "The requested resource is invalid, unknown, or not covered by the grant.",
"access_denied": "The resource owner denied the request.",
"invalid_dpop_proof": "The DPoP proof is invalid.",
"use_dpop_nonce": "The authorization server requires a nonce in the DPoP proof.",
diff --git a/authserver/grants.py b/authserver/grants.py
index f2d14f6..8e66806 100644
--- a/authserver/grants.py
+++ b/authserver/grants.py
@@ -18,6 +18,7 @@
from authserver.credentials import constant_time_equals, digest
from authserver.errors import OAuthError
from authserver.models import AuthorizationCode, Client, RefreshToken, TokenFamily
+from authserver.resources import audience_for, client_credentials_audience
from authserver.scopes import format_scope, parse_scope
from authserver.tokens import (
TokenResponse,
@@ -44,7 +45,7 @@ def authorization_code(
) -> TokenResponse:
"""Redeem an authorization code (OAuth 2.1 §4.1.3)."""
code, verifier, redirect_uri = _require(params, "code", "code_verifier", "redirect_uri")
- outcome = _redeem_code(client, code, verifier, redirect_uri, proof)
+ outcome = _redeem_code(client, code, verifier, redirect_uri, params.get("resource"), proof)
if isinstance(outcome, OAuthError):
raise outcome
return outcome
@@ -52,7 +53,12 @@ def authorization_code(
@transaction.atomic
def _redeem_code(
- client: Client, code: str, verifier: str, redirect_uri: str, proof: VerifiedProof
+ client: Client,
+ code: str,
+ verifier: str,
+ redirect_uri: str,
+ resource: str | None,
+ proof: VerifiedProof,
) -> TokenResponse | OAuthError:
record = AuthorizationCode.objects.select_for_update().filter(code_hash=digest(code)).first()
if record is None or record.client_id != client.pk:
@@ -81,12 +87,23 @@ def _redeem_code(
# to with dpop_jkt at the authorization endpoint.
return OAuthError("invalid_dpop_proof", "proof key differs from dpop_jkt")
+ try:
+ audience = audience_for(resource, record.resources)
+ except OAuthError as exc:
+ return exc
+
scope = parse_scope(record.scope)
- family = new_family(client, user_id=record.user_id, scope=scope, auth_time=record.auth_time)
+ family = new_family(
+ client,
+ user_id=record.user_id,
+ scope=scope,
+ resources=record.resources,
+ auth_time=record.auth_time,
+ )
record.family = family
record.save(update_fields=["family"])
access_token, expires_in = issue_access_token(
- client=client, scope=scope, jkt=proof.jkt, family=family
+ client=client, scope=scope, jkt=proof.jkt, audience=audience, family=family
)
refresh_token = None
if client.allows_grant(Client.GrantType.REFRESH_TOKEN):
@@ -97,7 +114,9 @@ def _redeem_code(
def refresh_token(client: Client, params: dict[str, str], proof: VerifiedProof) -> TokenResponse:
"""Rotate a refresh token (OAuth 2.1 §4.3), detecting reuse."""
(token,) = _require(params, "refresh_token")
- outcome = _rotate_refresh_token(client, token, params.get("scope"), proof)
+ outcome = _rotate_refresh_token(
+ client, token, params.get("scope"), params.get("resource"), proof
+ )
if isinstance(outcome, OAuthError):
raise outcome
return outcome
@@ -105,7 +124,11 @@ def refresh_token(client: Client, params: dict[str, str], proof: VerifiedProof)
@transaction.atomic
def _rotate_refresh_token(
- client: Client, token: str, requested_scope: str | None, proof: VerifiedProof
+ client: Client,
+ token: str,
+ requested_scope: str | None,
+ params_resource: str | None,
+ proof: VerifiedProof,
) -> TokenResponse | OAuthError:
record = RefreshToken.objects.select_for_update().filter(token_hash=digest(token)).first()
if record is None:
@@ -144,10 +167,15 @@ def _rotate_refresh_token(
if not set(scope) <= set(granted):
return OAuthError("invalid_scope", "scope exceeds the original grant")
+ try:
+ audience = audience_for(params_resource, family.resources)
+ except OAuthError as exc:
+ return exc
+
record.rotated_at = now
record.save(update_fields=["rotated_at"])
access_token, expires_in = issue_access_token(
- client=client, scope=scope, jkt=proof.jkt, family=family
+ client=client, scope=scope, jkt=proof.jkt, audience=audience, family=family
)
# RFC 6749 §6: the new refresh token carries the same scope as the old one,
# whatever this particular access token was narrowed to.
@@ -176,7 +204,10 @@ def client_credentials(
raise OAuthError("invalid_scope", "scope is malformed") from None
if not scope or not set(scope) <= set(client.scopes):
raise OAuthError("invalid_scope", "scope exceeds the client's registration")
- access_token, expires_in = issue_access_token(client=client, scope=scope, jkt=proof.jkt)
+ audience = client_credentials_audience(client, params.get("resource"))
+ access_token, expires_in = issue_access_token(
+ client=client, scope=scope, jkt=proof.jkt, audience=audience
+ )
return TokenResponse(access_token, expires_in, format_scope(scope))
diff --git a/authserver/management/commands/create_client.py b/authserver/management/commands/create_client.py
index 6ef09bc..d40675c 100644
--- a/authserver/management/commands/create_client.py
+++ b/authserver/management/commands/create_client.py
@@ -27,6 +27,13 @@ def add_arguments(self, parser: CommandParser) -> None:
)
parser.add_argument("--redirect-uri", dest="redirect_uris", action="append", default=[])
parser.add_argument("--scope", dest="scopes", action="append", default=[])
+ parser.add_argument(
+ "--resource",
+ dest="resources",
+ action="append",
+ default=[],
+ help="A resource (RFC 8707, from OAUTH_RESOURCES) the client may request tokens for.",
+ )
parser.add_argument(
"--introspect",
action="store_true",
@@ -42,6 +49,7 @@ def handle(self, *args: Any, **options: Any) -> None:
grant_types=options["grant_types"],
redirect_uris=options["redirect_uris"],
scopes=options["scopes"],
+ resources=options["resources"],
can_introspect=options["introspect"],
)
except ValueError as exc:
diff --git a/authserver/migrations/0002_resource_indicators.py b/authserver/migrations/0002_resource_indicators.py
new file mode 100644
index 0000000..5a88b8c
--- /dev/null
+++ b/authserver/migrations/0002_resource_indicators.py
@@ -0,0 +1,27 @@
+# Generated by Django 6.1.3 on 2026-11-26 08:52
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("authserver", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="authorizationcode",
+ name="resources",
+ field=models.JSONField(blank=True, default=list),
+ ),
+ migrations.AddField(
+ model_name="client",
+ name="resources",
+ field=models.JSONField(blank=True, default=list),
+ ),
+ migrations.AddField(
+ model_name="tokenfamily",
+ name="resources",
+ field=models.JSONField(blank=True, default=list),
+ ),
+ ]
diff --git a/authserver/models.py b/authserver/models.py
index 8366303..fd482ae 100644
--- a/authserver/models.py
+++ b/authserver/models.py
@@ -21,6 +21,8 @@
from django.db.models import Q
from django.utils import timezone
+from authserver.conf import server_settings
+
class Client(models.Model):
"""A registered OAuth client (RFC 6749 §2)."""
@@ -45,6 +47,9 @@ class GrantType(models.TextChoices):
redirect_uris = models.JSONField(default=list, blank=True)
grant_types = models.JSONField(default=list)
scopes = models.JSONField(default=list)
+ # RFC 8707: resources this client may request tokens for, beyond the
+ # default audience, which is always allowed.
+ resources = models.JSONField(default=list, blank=True)
# A resource server may introspect any token; other clients only their own.
can_introspect = models.BooleanField(default=False)
created_at = models.DateTimeField(default=timezone.now)
@@ -59,6 +64,9 @@ def is_confidential(self) -> bool:
def allows_grant(self, grant_type: str) -> bool:
return grant_type in self.grant_types
+ def allows_resource(self, resource: str) -> bool:
+ return resource == server_settings().audience or resource in self.resources
+
class AuthorizationCode(models.Model):
"""A one-time code from the authorization endpoint (OAuth 2.1 §4.1.2)."""
@@ -73,6 +81,8 @@ class AuthorizationCode(models.Model):
# RFC 9449 §10: the key the client committed to at the authorization
# endpoint, if it did. The token request must then prove that key.
dpop_jkt = models.CharField(max_length=128, blank=True)
+ # RFC 8707: the resources the request named. Empty means the default audience.
+ resources = models.JSONField(default=list, blank=True)
auth_time = models.DateTimeField()
expires_at = models.DateTimeField()
redeemed_at = models.DateTimeField(null=True, blank=True)
@@ -107,6 +117,8 @@ class RevocationReason(models.TextChoices):
settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE
)
scope = models.TextField()
+ # RFC 8707: what the grant covers; every refresh stays within it.
+ resources = models.JSONField(default=list, blank=True)
auth_time = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(default=timezone.now)
# An absolute ceiling: rotation extends a refresh token, never the family.
diff --git a/authserver/resources.py b/authserver/resources.py
new file mode 100644
index 0000000..ddfe22a
--- /dev/null
+++ b/authserver/resources.py
@@ -0,0 +1,50 @@
+"""Resource indicators (RFC 8707): which resource server a token is for.
+
+The configured ``OAUTH_RESOURCES`` are the only identifiers ever accepted, so
+membership is the whole validation. Every token has exactly one audience: a
+token good at two resource servers could be replayed at either.
+"""
+
+from authserver.conf import server_settings
+from authserver.errors import OAuthError
+from authserver.models import Client
+
+
+def known_resources(client: Client, requested: list[str]) -> list[str]:
+ """``requested`` without repeats; ``ValueError`` unless the server has
+ registered each one and ``client`` may ask for it."""
+ registered = set(server_settings().resources)
+ if not all(r in registered and client.allows_resource(r) for r in requested):
+ raise ValueError("unknown resource")
+ return list(dict.fromkeys(requested))
+
+
+def audience_for(requested: str | None, granted: list[str]) -> str:
+ """The audience for a token request (RFC 8707 §2.2).
+
+ ``granted`` is what the authorization covered; empty means the request
+ named no resource, which covers the default audience only. A request may
+ narrow the grant, never widen it.
+ """
+ conf = server_settings()
+ # Re-checked against the registry: dropping a resource from the settings
+ # also stops grants that already covered it.
+ allowed = [r for r in granted or [conf.audience] if r in conf.resources]
+ if not allowed:
+ raise OAuthError("invalid_target", "the grant's resources are no longer registered")
+ if requested is None:
+ if len(allowed) > 1:
+ raise OAuthError("invalid_target", "the grant covers several resources; name one")
+ return allowed[0]
+ if requested not in allowed:
+ raise OAuthError("invalid_target", "resource is outside the grant")
+ return requested
+
+
+def client_credentials_audience(client: Client, requested: str | None) -> str:
+ """A client acting for itself may name any resource it is registered for."""
+ if requested is None:
+ return server_settings().audience
+ if requested not in server_settings().resources or not client.allows_resource(requested):
+ raise OAuthError("invalid_target", "unknown resource")
+ return requested
diff --git a/authserver/templates/authserver/consent.html b/authserver/templates/authserver/consent.html
index 6b3196b..43988f6 100644
--- a/authserver/templates/authserver/consent.html
+++ b/authserver/templates/authserver/consent.html
@@ -6,6 +6,7 @@ {{ client.name }} wants to access your account
{% for name, description in scopes %}- {{ description }} ({{ name }})
{% endfor %}
+{% if resources %}Only at: {% for resource in resources %}{{ resource }}{% if not forloop.last %}, {% endif %}{% endfor %}.
{% endif %}
You will be sent back to {{ redirect_target }}.