Skip to content

Commit

Permalink
Gracefully handle invalid tokens and logout
Browse files Browse the repository at this point in the history
logout with old session state
  • Loading branch information
henrikhorluck committed Feb 28, 2024
1 parent 468e471 commit 9e1388a
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion apps/authentication/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth import logout
from django.core.exceptions import SuspiciousOperation
from josepy.errors import DeserializationError
from mozilla_django_oidc.auth import OIDCAuthenticationBackend

from apps.authentication.auth0 import auth0_client
Expand All @@ -15,6 +17,12 @@ def provider_logout(request):
# this is in accordance with
# https://auth0.com/docs/authenticate/login/logout/log-users-out-of-auth0#oidc-logout-endpoint-parameters

if "oidc_id_token" not in request.session:
# we probably have an old token from previous auth-regime
# we need to clear their cookies and previous session, which this hopefully will do
logout(request)
return f"{settings.BASE_URL}"

params = {
"id_token_hint": request.session["oidc_id_token"],
"client_id": settings.AUTH0_CLIENT_ID,
Expand Down Expand Up @@ -45,7 +53,12 @@ def get_or_create_user(self, access_token, id_token, payload):
if userinfo is None:
# this is modified from the source, since we do not want to call /userinfo on _every_ API-call
# this is kinda weird to have here, but ensures the access_token is verified in both DRF and elsewhere
userinfo = self.verify_token(access_token)
try:
userinfo = self.verify_token(access_token)
except DeserializationError:
LOGGER.debug("Login failed: invalid access token")
return None

if "https://online.ntnu.no" not in userinfo.get("aud", []):
raise SuspiciousOperation(
"Wrong audience, this token is not meant for us"
Expand Down

0 comments on commit 9e1388a

Please sign in to comment.