diff --git a/pyproject.toml b/pyproject.toml
index f8dbd93..6b736b5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,7 +14,7 @@ authors = [{name="Yaal Coop", email="contact@yaal.coop"}]
maintainers = [{name="Éloi Rivard", email="eloi@yaal.coop"}]
dependencies = [
- "authlib>=1.9.1",
+ "authlib>=1.10.0b1",
"babel>=2.14.0",
"cachelib>=0.10.0",
"flask>=3.1.2",
diff --git a/src/auth_playground/__init__.py b/src/auth_playground/__init__.py
index 74fe91e..301174f 100644
--- a/src/auth_playground/__init__.py
+++ b/src/auth_playground/__init__.py
@@ -134,17 +134,9 @@ def setup_oauth(app):
client_secret = config.get("client_secret")
client_auth_methods = [ClientSecretJWT()]
if config["token_endpoint_auth_method"] == KEY_METHOD:
- client_key = config["client_key"]
- # Authlib 1.9.4 reads a key given as text as an RSA key only.
- # TODO: with Authlib 1.10, pass client_key itself.
- client_secret = load_key(client_key)
+ client_secret = load_key(config["client_key"])
client_auth_methods.append(
- PrivateKeyJWT(
- alg=config["token_endpoint_auth_signing_alg"],
- # Authlib 1.9.4 does not put the kid of the key in the header.
- # TODO: remove with Authlib 1.10, which does.
- headers={"kid": client_key["kid"]},
- )
+ PrivateKeyJWT(alg=config["token_endpoint_auth_signing_alg"])
)
registry.register(
diff --git a/src/auth_playground/endpoints.py b/src/auth_playground/endpoints.py
index 98b3e21..8539429 100644
--- a/src/auth_playground/endpoints.py
+++ b/src/auth_playground/endpoints.py
@@ -39,8 +39,35 @@ def _get_metadata_document(url: str, timeout: int) -> dict:
return metadata
+class IssuerMismatchError(Exception):
+ """The issuer of the server metadata is not the issuer URL entered.
+
+ The issuer is ``None`` when the metadata has none.
+ """
+
+ def __init__(self, issuer):
+ super().__init__(issuer)
+ self.issuer = issuer
+
+
def fetch_server_metadata(issuer_url: str, timeout: int = 10) -> tuple[dict, str]:
- """Fetch server metadata from well-known OIDC or OAuth2 endpoints."""
+ """Fetch server metadata from well-known OIDC or OAuth2 endpoints.
+
+ Per OIDC Discovery §4.3 and RFC 8414 §3.3, the issuer of the metadata must
+ be the issuer URL the well-known URL is built from. ``issuer_url`` has no
+ trailing slash, and a trailing slash in the issuer is accepted.
+ """
+ metadata, server_type = _fetch_metadata_document(issuer_url, timeout)
+ issuer = metadata.get("issuer")
+ if not isinstance(issuer, str):
+ raise IssuerMismatchError(None)
+ if issuer.rstrip("/") != issuer_url:
+ raise IssuerMismatchError(issuer)
+ return metadata, server_type
+
+
+def _fetch_metadata_document(issuer_url: str, timeout: int) -> tuple[dict, str]:
+ """Fetch the OIDC metadata document, or else the OAuth2 one."""
oidc_url = f"{issuer_url}/.well-known/openid-configuration"
try:
return _get_metadata_document(oidc_url, timeout), "oidc"
@@ -54,7 +81,17 @@ def fetch_server_metadata(issuer_url: str, timeout: int = 10) -> tuple[dict, str
def _flash_metadata_error(exception: Exception) -> None:
"""Flash user-friendly error messages for metadata loading errors."""
- if isinstance(exception, requests.exceptions.ConnectionError):
+ if isinstance(exception, IssuerMismatchError) and exception.issuer is None:
+ flash(_("The server metadata has no issuer."), "error")
+ elif isinstance(exception, IssuerMismatchError):
+ flash(
+ _(
+ "The issuer of the server metadata is {issuer}, not the URL "
+ "you entered. A server must not use the issuer of another one."
+ ).format(issuer=exception.issuer),
+ "error",
+ )
+ elif isinstance(exception, requests.exceptions.ConnectionError):
flash(_("Cannot connect to the server. Please check the URL."), "error")
elif isinstance(exception, requests.exceptions.Timeout):
flash(_("Connection timeout. The server is not responding."), "error")
@@ -108,6 +145,7 @@ def load_server_metadata(
if not issuer_url:
return None
+ issuer_url = issuer_url.rstrip("/")
try:
metadata, server_type = fetch_server_metadata(issuer_url)
except Exception as e:
@@ -117,7 +155,7 @@ def load_server_metadata(
if update_config and g.server_config:
g.server_config.metadata = metadata
g.server_config.server_type = server_type
- g.server_config.issuer_url = issuer_url.rstrip("/")
+ g.server_config.issuer_url = issuer_url
# The client was set up before the metadata, which can change its
# signing algorithm.
auth_playground.setup_oauth(current_app)
diff --git a/src/auth_playground/forms.py b/src/auth_playground/forms.py
index adb10a2..7aeeda3 100644
--- a/src/auth_playground/forms.py
+++ b/src/auth_playground/forms.py
@@ -8,6 +8,7 @@
from flask import current_app
from flask import g
from flask import render_template
+from flask import session
from flask import url_for
from flask_babel import lazy_gettext as _
from flask_wtforms_htmx import HtmxFlaskForm
@@ -34,6 +35,7 @@
from wtforms.validators import Optional
from wtforms.widgets import CheckboxInput
from wtforms.widgets import ListWidget
+from wtforms.widgets import RadioInput
from wtforms.widgets import html_params
import auth_playground
@@ -58,7 +60,19 @@
from auth_playground.client_key import preferred_algorithm
from auth_playground.client_key import publish_key
from auth_playground.grants import GRANTS
+from auth_playground.grants import JWT_BEARER
from auth_playground.grants import advertised_grant_types
+from auth_playground.jwt_bearer import DEFAULT_LIFETIME
+from auth_playground.jwt_bearer import FORM_CLAIMS
+from auth_playground.jwt_bearer import KEY_SOURCE
+from auth_playground.jwt_bearer import PASTED_SOURCE
+from auth_playground.jwt_bearer import SECRET_SOURCE
+from auth_playground.jwt_bearer import assertion_alg
+from auth_playground.jwt_bearer import available_sources
+from auth_playground.jwt_bearer import build_assertion_preview
+from auth_playground.jwt_bearer import claims_object
+from auth_playground.jwt_bearer import jwt_bearer_preview
+from auth_playground.jwt_bearer import pasted_assertion
from auth_playground.session import server_metadata
from auth_playground.token_request import TOKEN_RESERVED_PARAMS
from auth_playground.token_request import client_credentials_preview
@@ -69,6 +83,7 @@
"refresh_token",
"client_credentials",
"password",
+ JWT_BEARER,
)
DEFAULT_REGISTERED_GRANT_TYPES = ["authorization_code", "refresh_token"]
@@ -654,17 +669,20 @@ def get_pkce_default():
return ""
-class RequestPreviewWidget:
- """Render the request that the form builds."""
+class PreviewWidget:
+ """Render what the form builds, with ``template``."""
+
+ def __init__(self, template):
+ self.template = template
def __call__(self, field, **kwargs):
kwargs.setdefault("id", field.id)
return Markup(
render_template(
- "_request_preview.html",
+ self.template,
attributes=Markup(html_params(**kwargs)),
label=field.label.text,
- request=field.build(field._form),
+ preview=field.build(field._form),
)
)
@@ -672,7 +690,7 @@ def __call__(self, field, **kwargs):
class RequestPreviewField(Field):
"""A read-only preview of the request that ``build(form)`` returns."""
- widget = RequestPreviewWidget()
+ widget = PreviewWidget("_request_preview.html")
def __init__(self, label=None, build=None, **kwargs):
super().__init__(label, **kwargs)
@@ -694,6 +712,12 @@ def scopes_field(default=None):
)
+class AssertionPreviewField(RequestPreviewField):
+ """A read-only preview of the assertion that ``build(form)`` returns."""
+
+ widget = PreviewWidget("_assertion_preview.html")
+
+
class RequestParamsForm(BaseForm):
"""Parameters common to the requests that obtain tokens.
@@ -835,6 +859,196 @@ class PasswordForm(RequestParamsForm):
request_tokens = ButtonField(_("Request tokens"), render_kw={"class": "primary"})
+class ChoiceRadioInput(RadioInput):
+ """A radio button that applies the render_kw of its choice."""
+
+ # WTForms 3.3.2 applies the render_kw of the choices to the options of a
+ # select, but not to radio buttons.
+ def __call__(self, field, **kwargs):
+ return super().__call__(field, **{**field.choice.render_kw, **kwargs})
+
+
+def assertion_source_choices():
+ """Offer the sources of the assertion, and disable those the client lacks."""
+ oauth_config = auth_playground.get_oauth_config(current_app)
+ available = available_sources(oauth_config)
+ if KEY_SOURCE in available:
+ key_label = _("Sign with the client key: {alg}").format(
+ alg=assertion_alg(KEY_SOURCE, oauth_config)
+ )
+ else:
+ key_label = _("Sign with the client key: this client has none.")
+ if SECRET_SOURCE in available:
+ secret_label = _("Sign with the client secret: {alg}").format(
+ alg=assertion_alg(SECRET_SOURCE, oauth_config)
+ )
+ else:
+ secret_label = _("Sign with the client secret: this client has none.")
+ return [
+ SelectChoice(
+ KEY_SOURCE, key_label, render_kw={"disabled": KEY_SOURCE not in available}
+ ),
+ SelectChoice(
+ SECRET_SOURCE,
+ secret_label,
+ render_kw={"disabled": SECRET_SOURCE not in available},
+ ),
+ SelectChoice(
+ PASTED_SOURCE,
+ _("Paste an assertion issued elsewhere"),
+ ),
+ ]
+
+
+def assertion_source_default():
+ """Return the first source of the assertion the client can use."""
+ return available_sources(auth_playground.get_oauth_config(current_app))[0]
+
+
+def signed_in_subject():
+ """Return the sub of the signed-in user, or an empty string."""
+ return (session.get("user") or {}).get("sub", "")
+
+
+def configured_client_id():
+ """Return the ID of the configured client, or an empty string."""
+ return auth_playground.get_oauth_config(current_app).get("client_id", "")
+
+
+def audience_choices():
+ """Offer the issuer and the token endpoint as the audience."""
+ metadata = server_metadata()
+ return [
+ SelectChoice(
+ "issuer", _("{url} (issuer)").format(url=metadata.get("issuer", ""))
+ ),
+ SelectChoice(
+ "token_endpoint",
+ _("{url} (token endpoint)").format(url=metadata.get("token_endpoint", "")),
+ ),
+ ]
+
+
+class JwtBearerForm(RequestParamsForm):
+ """Form to request tokens with a JWT that says who they are for (RFC 7523 §2.1)."""
+
+ endpoint = "oauth.jwt_bearer"
+ reserved_params = TOKEN_RESERVED_PARAMS | {"assertion"}
+
+ source = RadioField(
+ _("Assertion:"),
+ choices=assertion_source_choices,
+ default=assertion_source_default,
+ option_widget=ChoiceRadioInput(),
+ description=_(
+ "A client gets a key with private_key_jwt, and a secret with the "
+ "other confidential methods."
+ ),
+ )
+ assertion = TextAreaField(
+ _("Assertion (JWT):"),
+ description=_(
+ "Sent as is. The playground only decodes it, it does not check "
+ "the signature."
+ ),
+ render_kw={"rows": 5, "autocomplete": "off", "spellcheck": "false"},
+ ).triggered_by("source", on="change")
+ subject = StringField(
+ _("Subject (sub):"),
+ default=signed_in_subject,
+ description=_(
+ "Who the tokens are for. Filled with the sub of the signed-in user."
+ ),
+ render_kw={"autocomplete": "off"},
+ ).triggered_by("source", on="change")
+ issuer = StringField(
+ _("Issuer (iss):"),
+ default=configured_client_id,
+ description=_("The client ID, unless another party issues the assertion."),
+ ).triggered_by("source", on="change")
+ audience = SelectField(
+ _("Audience (aud):"),
+ choices=audience_choices,
+ default="issuer",
+ description=_("Per RFC 10070 §4, both are allowed for a grant."),
+ ).triggered_by("source", on="change")
+ lifetime = IntegerField(
+ _("Lifetime (seconds):"),
+ default=DEFAULT_LIFETIME,
+ description=_("From now to exp."),
+ render_kw={"min": 1},
+ ).triggered_by("source", on="change")
+ extra_claims = TextAreaField(
+ _("Extra claims:"),
+ description=_("A JSON object, added to the claims above."),
+ render_kw={"placeholder": '{"act": {"sub": "admin"}}'},
+ ).triggered_by("source", on="change")
+ scopes = scopes_field(default=get_scopes_default)
+ preview = RequestPreviewField(
+ _("Token request"), build=jwt_bearer_preview, wrapper=False
+ ).triggered_by("*")
+ assertion_preview = AssertionPreviewField(
+ _("Assertion"), build=build_assertion_preview, wrapper=False
+ ).triggered_by("*")
+ request_tokens = ButtonField(_("Request tokens"), render_kw={"class": "primary"})
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ signing = self.signing()
+ show_field(self.assertion, not signing)
+ for field in (
+ self.subject,
+ self.issuer,
+ self.audience,
+ self.lifetime,
+ self.extra_claims,
+ ):
+ show_field(field, signing)
+
+ def signing(self):
+ """Tell whether the playground signs the assertion."""
+ return self.source.data != PASTED_SOURCE
+
+ def validate_source(self, field):
+ oauth_config = auth_playground.get_oauth_config(current_app)
+ if field.data not in available_sources(oauth_config):
+ raise ValidationError(_("This client cannot sign the assertion this way."))
+
+ def validate_assertion(self, field):
+ if not self.signing() and not pasted_assertion(self):
+ raise ValidationError(_("Paste the assertion."))
+
+ def validate_subject(self, field):
+ if self.signing() and not field.data:
+ raise ValidationError(_("Enter who the tokens are for."))
+
+ def validate_issuer(self, field):
+ if self.signing() and not field.data:
+ raise ValidationError(_("Enter who issues the assertion."))
+
+ def validate_lifetime(self, field):
+ if not self.signing():
+ # Like Optional, forget that the hidden value is not a number.
+ field.errors[:] = []
+ return
+ if field.data is not None and field.data < 1:
+ raise ValidationError(_("Enter a number of seconds, 1 or more."))
+
+ def validate_extra_claims(self, field):
+ if not self.signing() or not field.data:
+ return
+
+ claims = claims_object(field.data)
+ if claims is None:
+ raise ValidationError(_("The extra claims must be a JSON object."))
+ if form_claims := [name for name in FORM_CLAIMS if name in claims]:
+ raise ValidationError(
+ _("The form already sets these claims: {claims}.").format(
+ claims=", ".join(form_claims)
+ )
+ )
+
+
def grant_label(grant):
"""Mark the label of a deprecated grant type, or one the server does not advertise."""
marks = []
@@ -852,7 +1066,7 @@ def grant_label(grant):
def get_grant_choices():
"""Group the grant types, and label the ones the server does not advertise."""
return [
- SelectChoice(grant.value, grant_label(grant), optgroup=grant.group)
+ SelectChoice(grant.name, grant_label(grant), optgroup=grant.group)
for grant in GRANTS
]
diff --git a/src/auth_playground/grants.py b/src/auth_playground/grants.py
index 87eed03..91b30fa 100644
--- a/src/auth_playground/grants.py
+++ b/src/auth_playground/grants.py
@@ -2,6 +2,7 @@
from dataclasses import dataclass
+from authlib.oauth2.rfc7523 import JWTBearerGrant
from flask import session
from flask_babel import lazy_gettext as _
@@ -10,6 +11,8 @@
# Per RFC 8414 §2, when the server does not publish grant_types_supported.
DEFAULT_GRANT_TYPES = ["authorization_code", "implicit"]
+JWT_BEARER = JWTBearerGrant.GRANT_TYPE
+
def advertised_grant_types():
"""Return the grant types the server advertises."""
@@ -31,6 +34,13 @@ class Grant:
user: bool = True
# The user signs in at the provider, which keeps a session for them.
provider_session: bool = False
+ # The name in the playground URLs, for a grant type that is a URN.
+ short_name: str | None = None
+
+ @property
+ def name(self):
+ """Return the name of the grant type in the playground URLs."""
+ return self.short_name or self.value
@property
def advertised(self):
@@ -83,9 +93,22 @@ def advertised(self):
),
deprecated=True,
),
+ Grant(
+ JWT_BEARER,
+ _("JWT bearer"),
+ _("Direct"),
+ _(
+ "The client sends a signed JWT that says who the tokens are for. "
+ "The provider checks the signature and the claims, then issues tokens "
+ "for the subject."
+ ),
+ (("RFC 7523 §2.1", "https://www.rfc-editor.org/rfc/rfc7523#section-2.1"),),
+ short_name="jwt_bearer",
+ ),
)
GRANTS_BY_VALUE = {grant.value: grant for grant in GRANTS}
+GRANTS_BY_NAME = {grant.name: grant for grant in GRANTS}
def tokens_grant():
@@ -94,6 +117,6 @@ def tokens_grant():
return GRANTS_BY_VALUE.get(grant, GRANTS[0])
-def get_grant(value):
- """Return the grant type ``value``, or else the one that obtained the tokens."""
- return GRANTS_BY_VALUE.get(value) or tokens_grant()
+def get_grant(name):
+ """Return the grant type called ``name``, or else the one that obtained the tokens."""
+ return GRANTS_BY_NAME.get(name) or tokens_grant()
diff --git a/src/auth_playground/jwt_bearer.py b/src/auth_playground/jwt_bearer.py
new file mode 100644
index 0000000..2832015
--- /dev/null
+++ b/src/auth_playground/jwt_bearer.py
@@ -0,0 +1,276 @@
+"""Assertions of the JWT bearer grant (RFC 7523 §2.1)."""
+
+import json
+import math
+import time
+from dataclasses import dataclass
+from dataclasses import field
+
+from authlib.oauth2.rfc7523 import JWTBearerGrant
+from flask import current_app
+from flask_babel import format_datetime
+from flask_babel import gettext as _
+from joserfc import jws
+from joserfc.errors import JoseError
+from joserfc.jwk import OctKey
+
+import auth_playground
+from auth_playground.client_key import load_key
+from auth_playground.grants import JWT_BEARER
+from auth_playground.preview import GENERATED
+from auth_playground.preview import NOW
+from auth_playground.session import server_metadata
+from auth_playground.token_request import signed_header
+from auth_playground.token_request import token_preview
+
+KEY_SOURCE = "key"
+SECRET_SOURCE = "secret"
+PASTED_SOURCE = "paste"
+
+# A MAC with the client secret, like client_secret_jwt.
+SECRET_ALG = "HS256"
+
+DEFAULT_LIFETIME = 300
+
+# The server metadata the audience can be.
+AUDIENCES = ("issuer", "token_endpoint")
+
+# The claims shown as dates under a decoded assertion.
+TIME_CLAIMS = ("iat", "nbf", "exp")
+
+# The claims the form sets. The extra claims cannot replace them.
+FORM_CLAIMS = ("iss", "sub", "aud", "iat", "exp")
+
+
+@dataclass
+class AssertionPreview:
+ """The assertion of the grant, as shown to the user."""
+
+ note: str
+ header: str | None = None
+ claims: str | None = None
+ dates: list[tuple[str, str]] = field(default_factory=list)
+ notices: list[tuple[str, str]] = field(default_factory=list)
+
+
+def json_object(text, **kwargs):
+ """Return the JSON object in ``text``, or ``None`` when it is not one."""
+ try:
+ data = json.loads(text, **kwargs)
+ except ValueError:
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def reject_constant(name):
+ """Refuse NaN and Infinity, which are not JSON (RFC 8259 §6)."""
+ raise ValueError(name)
+
+
+def claims_object(text):
+ """Return the JSON object of claims to sign, or ``None`` when it is not one."""
+ return json_object(text, parse_constant=reject_constant)
+
+
+def extra_claims(form):
+ """Return the extra claims of the form, or an empty dict."""
+ return claims_object(form.extra_claims.data or "{}") or {}
+
+
+def audience(form):
+ """Return the audience the form chose: the issuer or the token endpoint."""
+ if form.audience.data not in AUDIENCES:
+ return ""
+ return server_metadata().get(form.audience.data, "")
+
+
+def assertion_alg(source, oauth_config):
+ """Return the algorithm that signs the assertion."""
+ if source == SECRET_SOURCE:
+ return SECRET_ALG
+ return oauth_config["token_endpoint_auth_signing_alg"]
+
+
+def assertion_header(source, oauth_config):
+ """Return the header of the assertion the playground signs.
+
+ Like Authlib, it takes the kid of the signing key.
+ """
+ kid = signing_key(source, oauth_config).kid
+ return signed_header(assertion_alg(source, oauth_config), kid)
+
+
+def signing_key(source, oauth_config):
+ """Return the key that signs the assertion."""
+ if source == SECRET_SOURCE:
+ return OctKey.import_key(oauth_config["client_secret"])
+ return load_key(oauth_config["client_key"])
+
+
+def sign_assertion(form):
+ """Sign the assertion the form describes."""
+ oauth_config = auth_playground.get_oauth_config(current_app)
+ source = form.source.data
+ # Authlib adds the kid of the key.
+ header = signed_header(assertion_alg(source, oauth_config))
+ issued_at = int(time.time())
+ return JWTBearerGrant.sign(
+ signing_key(source, oauth_config),
+ issuer=form.issuer.data,
+ audience=audience(form),
+ subject=form.subject.data,
+ issued_at=issued_at,
+ expires_at=issued_at + form.lifetime.data,
+ claims=extra_claims(form),
+ header=header,
+ )
+
+
+def pasted_assertion(form):
+ """Return the pasted assertion, without the spaces a copy may add."""
+ return "".join((form.assertion.data or "").split())
+
+
+def decode_assertion(text):
+ """Return the header and the claims of a JWT, or ``None``.
+
+ The signature is not checked.
+ """
+ try:
+ token = jws.extract_compact(text.encode())
+ except JoseError:
+ return None
+
+ claims = json_object(token.payload)
+ if claims is None:
+ return None
+ return token.protected, claims
+
+
+def assertion_subject(form):
+ """Return who the assertion is for, or ``None`` when it does not say."""
+ if form.signing():
+ return form.subject.data
+ decoded = decode_assertion(pasted_assertion(form))
+ return decoded[1].get("sub") if decoded else None
+
+
+def jwt_bearer_preview(form):
+ """Return the JWT bearer token request built from the form.
+
+ Like Authlib, it leaves out an empty assertion.
+ """
+ assertion = GENERATED if form.signing() else pasted_assertion(form)
+ params = [("assertion", assertion)] if assertion else []
+ return token_preview(form, JWT_BEARER, params)
+
+
+def build_assertion_preview(form):
+ """Return the assertion built from the form, or the pasted one, decoded."""
+ if not form.signing():
+ return pasted_assertion_preview(pasted_assertion(form))
+
+ oauth_config = auth_playground.get_oauth_config(current_app)
+ if form.source.data not in available_sources(oauth_config):
+ return AssertionPreview(_("This client cannot sign the assertion."))
+
+ header = assertion_header(form.source.data, oauth_config)
+ claims = {"iss": form.issuer.data or "", "aud": audience(form)}
+ if form.subject.data:
+ claims["sub"] = form.subject.data
+ claims["iat"] = NOW
+ claims["exp"] = f"[now + {form.lifetime.data or 0} s]"
+ # In the order Authlib writes them: the extra claims come last.
+ claims["jti"] = GENERATED
+ claims.update(extra_claims(form))
+ return AssertionPreview(
+ _("Signed with {alg} when the request is sent").format(alg=header["alg"]),
+ header=json.dumps(header),
+ claims=json.dumps(claims, indent=2),
+ )
+
+
+def pasted_assertion_preview(text):
+ """Return the pasted assertion decoded, with what the provider may refuse."""
+ note = _("Decoded, the signature is not checked")
+ if not text:
+ return AssertionPreview(note)
+
+ decoded = decode_assertion(text)
+ if decoded is None:
+ return AssertionPreview(
+ note,
+ notices=[
+ (
+ "warning",
+ _("This is not a JWT the playground can decode. It is sent as is."),
+ )
+ ],
+ )
+
+ header, claims = decoded
+ dates = {name: format_date(claims.get(name)) for name in TIME_CLAIMS}
+ return AssertionPreview(
+ note,
+ header=json.dumps(header),
+ claims=json.dumps(claims, indent=2),
+ dates=[(name, date) for name, date in dates.items() if date],
+ notices=assertion_notices(claims, dates["exp"]),
+ )
+
+
+def format_date(value):
+ """Return a NumericDate claim as a date, or ``None`` when it is not one."""
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ if not math.isfinite(value):
+ return None
+ try:
+ return format_datetime(value)
+ except (ValueError, OverflowError, OSError):
+ return None
+
+
+def assertion_notices(claims, exp_date):
+ """Return why the provider may refuse the claims of a pasted assertion."""
+ notices = []
+ if exp_date and claims["exp"] < time.time():
+ notices.append(
+ (
+ "warning",
+ _(
+ "The assertion expired on {date}. The provider will refuse it."
+ ).format(date=exp_date),
+ )
+ )
+
+ metadata = server_metadata()
+ aud = claims.get("aud")
+ audiences = {
+ value
+ for value in (aud if isinstance(aud, list) else [aud])
+ if isinstance(value, str)
+ }
+ if audiences & {metadata.get("issuer"), metadata.get("token_endpoint")}:
+ return notices
+
+ notices.append(
+ (
+ "warning",
+ _(
+ "The audience is neither the issuer nor the token endpoint. "
+ "The provider will likely refuse the assertion."
+ ),
+ )
+ )
+ return notices
+
+
+def available_sources(oauth_config):
+ """Return the sources of the assertion the client can use."""
+ sources = []
+ if oauth_config.get("client_key"):
+ sources.append(KEY_SOURCE)
+ if oauth_config.get("client_secret"):
+ sources.append(SECRET_SOURCE)
+ return [*sources, PASTED_SOURCE]
diff --git a/src/auth_playground/oauth.py b/src/auth_playground/oauth.py
index 4807845..7fcc036 100644
--- a/src/auth_playground/oauth.py
+++ b/src/auth_playground/oauth.py
@@ -42,13 +42,18 @@
from auth_playground.forms import AuthorizationParamsForm
from auth_playground.forms import ClientCredentialsForm
from auth_playground.forms import DynamicRegistrationForm
+from auth_playground.forms import JwtBearerForm
from auth_playground.forms import LogoutLocalForm
from auth_playground.forms import LogoutParamsForm
from auth_playground.forms import PasswordForm
from auth_playground.forms import RefreshTokenForm
from auth_playground.forms import UnregisterClientForm
from auth_playground.forms import UserInfoForm
+from auth_playground.grants import JWT_BEARER
from auth_playground.grants import tokens_grant
+from auth_playground.jwt_bearer import assertion_subject
+from auth_playground.jwt_bearer import pasted_assertion
+from auth_playground.jwt_bearer import sign_assertion
from auth_playground.pages import render_tokens_page
from auth_playground.session import server_metadata
from auth_playground.token_request import extra_token_params
@@ -466,11 +471,11 @@ def fetch_tokens(grant_type, form=None, **params):
return None
-def render_grant_form(grant_type, form):
- """Render the request tab again, with the form of ``grant_type``."""
+def render_grant_form(grant, form):
+ """Render the request tab again, with the form of the grant type called ``grant``."""
if "csrf_token" in form.errors:
flash(_("Invalid request"), "error")
- return render_tokens_page("request", grant=grant_type, grant_form=form)
+ return render_tokens_page("request", grant=grant, grant_form=form)
@bp.route("/token/client-credentials", methods=["POST"])
@@ -519,15 +524,55 @@ def password():
forget_tokens()
store_token(token, "password", requested_scope=scope or None)
+ sign_in_user(claims, form.username.data)
+ return redirect(url_for("routes.tokens", tab="current"))
+
+
+@bp.route("/token/jwt-bearer", methods=["POST"])
+@server_config_needed
+def jwt_bearer():
+ """Request tokens with a JWT that says who they are for."""
+ form = JwtBearerForm()
+ if not form.validate_on_submit():
+ return render_grant_form("jwt_bearer", form)
+
+ if not form.signing():
+ assertion = pasted_assertion(form)
+ else:
+ try:
+ assertion = sign_assertion(form)
+ except (JoseError, ValueError) as exc:
+ flash(
+ _("The assertion could not be signed: {error}").format(error=exc),
+ "error",
+ )
+ return render_grant_form("jwt_bearer", form)
+
+ scope = requested_scope(form)
+ token = fetch_tokens(JWT_BEARER, form, assertion=assertion, scope=scope)
+ if token is None:
+ return render_grant_form("jwt_bearer", form)
+
+ claims, reason = read_id_token(token)
+ if reason:
+ flash(_("The tokens are not kept. {reason}").format(reason=reason), "error")
+ return render_grant_form("jwt_bearer", form)
+
+ forget_tokens()
+ store_token(token, JWT_BEARER, requested_scope=scope or None)
+ sign_in_user(claims, assertion_subject(form))
+ return redirect(url_for("routes.tokens", tab="current"))
+
+
+def sign_in_user(claims, subject):
+ """Sign in the user of the ID token, or else say who the tokens are for."""
session["user"] = claims
if claims:
flash(_("You have been successfully logged in."), "success")
+ elif subject:
+ flash(_("Tokens obtained for {subject}.").format(subject=subject), "success")
else:
- flash(
- _("Tokens obtained for {username}.").format(username=form.username.data),
- "success",
- )
- return redirect(url_for("routes.tokens", tab="current"))
+ flash(_("Tokens obtained."), "success")
def read_id_token(token):
@@ -535,7 +580,7 @@ def read_id_token(token):
When the reason is ``None``, the token can be kept. The claims are then
``None`` if the token has no ID token.
- No nonce is checked. The password grant sends none, and neither does an
+ No nonce is checked. The direct grant types send none, and neither does an
authorization request without the openid scope. Per OIDC Core §12.2, a
refreshed ID token should have none, and Authlib does not compare it with
the original ID token.
@@ -727,13 +772,19 @@ def refresh():
def bearer_token():
- """Return the access token alone, to send it to the provider as it is.
+ """Return the access token to send to the provider as it is.
With an expiry date or a refresh token, Authlib could refuse the token
- before sending it, or refresh it without the playground knowing.
+ before sending it, or refresh it without the playground knowing. The ID
+ token claims let Authlib check the UserInfo sub (OIDC Core §5.3.2).
"""
token = session.get("token", {})
- return {key: token[key] for key in ("access_token", "token_type") if token.get(key)}
+ bearer = {
+ key: token[key] for key in ("access_token", "token_type") if token.get(key)
+ }
+ if session.get("user"):
+ bearer["userinfo"] = session["user"]
+ return bearer
@bp.route("/userinfo", methods=["POST"])
@@ -766,6 +817,8 @@ def userinfo():
error = _("The response is not JSON.")
except requests.RequestException as exc:
error = get_response_error(exc) or www_authenticate(exc) or exc
+ except (JoseError, RuntimeError, KeyError) as exc:
+ error = _("The signed response is not valid: {error}").format(error=exc)
except (TypeError, ValueError):
error = _("The response is not a JSON object.")
else:
diff --git a/src/auth_playground/pages.py b/src/auth_playground/pages.py
index 8c0212b..cb819e4 100644
--- a/src/auth_playground/pages.py
+++ b/src/auth_playground/pages.py
@@ -11,6 +11,7 @@
from auth_playground.forms import AuthorizationParamsForm
from auth_playground.forms import ClientCredentialsForm
from auth_playground.forms import GrantForm
+from auth_playground.forms import JwtBearerForm
from auth_playground.forms import LogoutLocalForm
from auth_playground.forms import LogoutParamsForm
from auth_playground.forms import PasswordForm
@@ -24,13 +25,14 @@
"authorization_code": AuthorizationParamsForm,
"client_credentials": ClientCredentialsForm,
"password": PasswordForm,
+ "jwt_bearer": JwtBearerForm,
}
def render_tokens_page(tab, grant=None, grant_form=None):
"""Render a tab of the tokens page.
- The grant type comes from ``grant``, or else from the query string.
+ The grant type is called ``grant``, or else is in the query string.
"""
oauth_config = auth_playground.get_oauth_config(current_app)
logout_params_form = LogoutParamsForm(
@@ -46,8 +48,8 @@ def render_tokens_page(tab, grant=None, grant_form=None):
grant_forms = {}
if tab == "request":
grant_forms = {
- "grant_selector": GrantForm(data={"grant": grant.value}),
- "grant_form": grant_form or GRANT_FORMS[grant.value](),
+ "grant_selector": GrantForm(data={"grant": grant.name}),
+ "grant_form": grant_form or GRANT_FORMS[grant.name](),
}
return render_template(
diff --git a/src/auth_playground/templates/_assertion_preview.html b/src/auth_playground/templates/_assertion_preview.html
new file mode 100644
index 0000000..8e5b111
--- /dev/null
+++ b/src/auth_playground/templates/_assertion_preview.html
@@ -0,0 +1,18 @@
+
+ {{ label }} {{ preview.note }}
+ {% for type, message in preview.notices %}
+ {{ message }}
+ {% endfor %}
+ {% if preview.claims %}
+
{% trans %}Header{% endtrans %}
+{{ preview.header }}
+
+{% trans %}Claims{% endtrans %}
+{{ preview.claims }}
+{%- if preview.dates %}
+
+{% trans %}Dates{% endtrans %}
+{% for name, date in preview.dates %}{{ name }}: {{ date }}
+{% endfor %}{% endif %}