Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#270 - Add middleware to refresh access token #343

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
29 changes: 27 additions & 2 deletions django_auth_adfs/backend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from datetime import datetime, timedelta

import jwt
from django.contrib.auth import get_user_model
Expand Down Expand Up @@ -394,14 +395,38 @@ def authenticate(self, request=None, authorization_code=None, **kwargs):
logger.debug("Authentication backend was called but no authorization code was received")
return

# If there's no request object, we pass control to the next authentication backend
if request is None:
logger.debug("Authentication backend was called without request")
return

# If loaded data is too old, reload it again
provider_config.load_config()

adfs_response = self.exchange_auth_code(authorization_code, request)
access_token = adfs_response["access_token"]
user = self.process_access_token(access_token, adfs_response)
user = self._process_adfs_response(request, adfs_response)
return user

def _process_adfs_response(self, request, adfs_response):
user = self.process_access_token(adfs_response['access_token'], adfs_response)
request.session['_adfs_access_token'] = adfs_response['access_token']
expiry = datetime.now() + timedelta(seconds=adfs_response['expires_in'])
request.session['_adfs_token_expiry'] = expiry.isoformat()
if 'refresh_token' in adfs_response:
request.session['_adfs_refresh_token'] = adfs_response['refresh_token']
request.session.save()
return user

def refresh_access_token(self, request, refresh_token):
provider_config.load_config()
response = provider_config.session.post(
provider_config.token_endpoint,
data=f'grant_type=refresh_token&refresh_token={refresh_token}'
)
response.raise_for_status()
adfs_response = response.json()
self._process_adfs_response(request, adfs_response)


class AdfsAccessTokenBackend(AdfsBaseBackend):
"""
Expand Down
1 change: 1 addition & 0 deletions django_auth_adfs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def __init__(self):
self.USERNAME_CLAIM = "winaccountname"
self.GUEST_USERNAME_CLAIM = None
self.JWT_LEEWAY = 0
self.REFRESH_THRESHOLD = timedelta(minutes=5)
self.CUSTOM_FAILED_RESPONSE_VIEW = lambda request, error_message, status: render(
request, 'django_auth_adfs/login_failed.html', {'error_message': error_message}, status=status
)
Expand Down
30 changes: 30 additions & 0 deletions django_auth_adfs/middleware.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
"""
Based on https://djangosnippets.org/snippets/1179/
"""
import logging
from datetime import datetime
from re import compile

from django.conf import settings as django_settings
from django.contrib import auth
from django.contrib.auth import logout
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from requests import HTTPError

from django_auth_adfs.backend import AdfsAuthCodeBackend
from django_auth_adfs.exceptions import MFARequired
from django_auth_adfs.config import settings

Expand All @@ -19,6 +26,8 @@
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
LOGIN_EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

logger = logging.getLogger("django_auth_adfs")


class LoginRequiredMiddleware:
"""
Expand Down Expand Up @@ -49,3 +58,24 @@ def __call__(self, request):
return redirect_to_login('django_auth_adfs:login-force-mfa')

return self.get_response(request)


def adfs_refresh_middleware(get_response):
def middleware(request):
try:
backend_str = request.session[auth.BACKEND_SESSION_KEY]
except KeyError:
pass
else:
backend = auth.load_backend(backend_str)
if isinstance(backend, AdfsAuthCodeBackend):
now = datetime.now() + settings.REFRESH_THRESHOLD
expiry = datetime.fromisoformat(request.session['_adfs_token_expiry'])
if now > expiry:
try:
backend.refresh_access_token(request, request.session['_adfs_refresh_token'])
except (PermissionDenied, HTTPError) as error:
logger.debug("Error refreshing access token: %s", error)
logout(request)
return get_response(request)
return middleware
1 change: 1 addition & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

'django_auth_adfs.middleware.adfs_refresh_middleware',
'django_auth_adfs.middleware.LoginRequiredMiddleware',
)

Expand Down
Loading
Loading