Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/auth_playground/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,12 @@ class RefreshTokenForm(BaseForm):
refresh = SubmitField(_("Renew tokens"))


class UserInfoForm(BaseForm):
"""Form to call the UserInfo endpoint with the access token."""

userinfo = SubmitField(_("Get user info"))


def is_loopback_address(hostname):
"""Tell whether the hostname is a loopback IP address."""
try:
Expand Down
74 changes: 73 additions & 1 deletion src/auth_playground/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
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 tokens_grant
from auth_playground.pages import render_tokens_page
from auth_playground.session import server_metadata
Expand Down Expand Up @@ -93,9 +94,19 @@ def get_response_error(exc: requests.RequestException) -> str | None:
return error if isinstance(error, str) else None


def www_authenticate(exc: requests.RequestException) -> str | None:
"""Get the WWW-Authenticate header of an error response.

Per RFC 6750 §3, a protected resource gives its error there.
"""
if exc.response is None:
return None
return exc.response.headers.get("WWW-Authenticate")


def forget_tokens():
"""Forget the user and the tokens."""
for key in ("user", "token", "token_info"):
for key in ("user", "token", "token_info", "userinfo"):
session.pop(key, None)


Expand Down Expand Up @@ -400,6 +411,7 @@ def store_token(token, grant_type, requested_scope=None, pkce=None):
"""
old_token = session.get("token", {})
old_info = session.get("token_info", {})
session.pop("userinfo", None)
session["token"] = {
"access_token": token.get("access_token"),
"refresh_token": token.get("refresh_token") or old_token.get("refresh_token"),
Expand Down Expand Up @@ -663,3 +675,63 @@ def refresh():
)

return redirect(url_for("routes.tokens"))


def bearer_token():
"""Return the access token alone, to send it 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.
"""
token = session.get("token", {})
return {key: token[key] for key in ("access_token", "token_type") if token.get(key)}


@bp.route("/userinfo", methods=["POST"])
@server_config_needed
def userinfo():
"""Call the UserInfo endpoint with the access token."""
form = UserInfoForm()
if not form.validate_on_submit():
flash(_("Invalid request"), "error")
return redirect(url_for("routes.tokens"))

if not session.get("token", {}).get("access_token"):
flash(_("No access token available"), "error")
return redirect(url_for("routes.tokens"))

if not tokens_grant().user:
flash(_("These tokens are not tied to a user."), "error")
return redirect(url_for("routes.tokens"))

endpoint = server_metadata().get("userinfo_endpoint")
if not endpoint:
flash(_("The provider has no UserInfo endpoint."), "error")
return redirect(url_for("routes.tokens"))

try:
claims = auth_playground.oauth.default.userinfo(
token=bearer_token(), timeout=10
)
except AuthlibBaseError as exc:
error = exc.description or exc.error
except requests.JSONDecodeError:
error = _("The response is not JSON.")
except requests.RequestException as exc:
error = get_response_error(exc) or www_authenticate(exc) or exc
except (TypeError, ValueError):
error = _("The response is not a JSON object.")
else:
session["userinfo"] = {
"endpoint": endpoint,
"received_at": int(time.time()),
"claims": dict(claims),
}
flash(_("User info received"), "success")
return redirect(url_for("routes.tokens"))

flash(
_("An error happened during the UserInfo request: {error}").format(error=error),
"error",
)
return redirect(url_for("routes.tokens"))
4 changes: 4 additions & 0 deletions src/auth_playground/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
from auth_playground.forms import LogoutParamsForm
from auth_playground.forms import PasswordForm
from auth_playground.forms import RefreshTokenForm
from auth_playground.forms import UserInfoForm
from auth_playground.grants import get_grant
from auth_playground.grants import tokens_grant
from auth_playground.session import server_metadata

GRANT_FORMS = {
"authorization_code": AuthorizationParamsForm,
Expand Down Expand Up @@ -52,6 +54,8 @@ def render_tokens_page(tab, grant=None, grant_form=None):
"tokens.html",
tab=tab,
refresh_form=RefreshTokenForm(),
userinfo_form=UserInfoForm(),
userinfo_endpoint=server_metadata().get("userinfo_endpoint"),
grant=grant,
tokens_grant=tokens_grant(),
public_client=oauth_config.get("token_endpoint_auth_method") == PUBLIC_METHOD,
Expand Down
11 changes: 11 additions & 0 deletions src/auth_playground/templates/_tokens.html
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,17 @@ <h4>{% trans %}Token metadata{% endtrans %}</h4>
</article>
{% endif %}

{% if session.userinfo %}
<article>
<h3>{% trans %}UserInfo response{% endtrans %}</h3>
<ul>
<li><strong>{% trans %}UserInfo endpoint:{% endtrans %}</strong> {{ session.userinfo.endpoint }}</li>
<li><strong>{% trans %}Received at:{% endtrans %}</strong> {{ session.userinfo.received_at|datetimeformat }}</li>
</ul>
<pre class="token-response"><code>{{ session.userinfo.claims|tojson(indent=2) }}</code></pre>
</article>
{% endif %}

<div class="grid">
{% if session.token and session.token.access_token %}
<article>
Expand Down
5 changes: 5 additions & 0 deletions src/auth_playground/templates/tokens.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
<p><small>{% trans %}Silent refresh — auth_time and acr stay unchanged.{% endtrans %}</small></p>
{% endif %}
{% endif %}
{% if userinfo_endpoint and tokens_grant.user and session.token.access_token %}
{% call render_form(userinfo_form, url_for('oauth.userinfo'), id="userinfo-form") %}
{{ userinfo_form.userinfo() }}
{% endcall %}
{% endif %}
{% include "_tokens.html" %}
{% if not tokens_grant.provider_session %}
{% call render_form(logout_local_form, url_for('oauth.logout_local'), id="forget-tokens-form") %}
Expand Down
Loading
Loading