Skip to content

Commit

Permalink
Fix infinite redirect during token verification if login page is acce…
Browse files Browse the repository at this point in the history
…ssed
  • Loading branch information
timonegk committed May 18, 2024
1 parent 0c1df29 commit 3a76171
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/simple_openid_connect/integrations/django/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,29 @@ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:

def __call__(self, request: HttpRequest) -> HttpResponse:
response = self.get_response(request)

# if we are already trying to log in, no redirect should happen
if request.path == resolve_url(settings.LOGIN_URL):
return response

# if the user is not logged in, also no redirect should happen
openid_session_id = request.session.get("openid_session")
if not openid_session_id:
return response

# the refresh token has a long validity, the access token expires quickly
openid_session = OpenidSession.objects.get(id=openid_session_id)
refresh_token = openid_session.refresh_token
session_valid_until = openid_session.access_token_expiry
access_token_valid = (
session_valid_until is not None
and session_valid_until > datetime.now(timezone.utc)
)
# if the access token is valid, everything is fine
if access_token_valid:
return response

# try to refresh the access token with the refresh token
logger.debug("access token expired, trying to refresh")
client = OpenidAppConfig.get_instance().get_client(request)
exchange_response = client.exchange_refresh_token(refresh_token)
Expand All @@ -42,4 +51,5 @@ def __call__(self, request: HttpRequest) -> HttpResponse:
openid_session.save()
return response
else:
# the refresh token is also expired, redirect to login
return HttpResponseRedirect(resolve_url(settings.LOGIN_URL))

0 comments on commit 3a76171

Please sign in to comment.