Skip to content

Commit c754690

Browse files
committed
add 'Authorization' to 'Vary' header in the middleware
1 parent b6af819 commit c754690

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

oauth2_provider/middleware.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from django.contrib.auth import authenticate
2+
from django.utils.cache import patch_vary_headers
23

34

45
class OAuth2TokenMiddleware(object):
@@ -16,6 +17,9 @@ class OAuth2TokenMiddleware(object):
1617
tries to authenticate user with the OAuth2 access token and set request.user field. Setting
1718
also request._cached_user field makes AuthenticationMiddleware use that instead of the one from
1819
the session.
20+
21+
It also adds 'Authorization' to the 'Vary' header. So that django's cache middleware or a
22+
reverse proxy can create proper cache keys
1923
"""
2024
def process_request(self, request):
2125
# do something only if request contains a Bearer token
@@ -24,3 +28,7 @@ def process_request(self, request):
2428
user = authenticate(request=request)
2529
if user:
2630
request.user = request._cached_user = user
31+
32+
def process_response(self, request, response):
33+
patch_vary_headers(response, ('Authorization',))
34+
return response

oauth2_provider/tests/test_auth_backends.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from django.contrib.auth.models import AnonymousUser
44
from django.utils.timezone import now, timedelta
55
from django.conf.global_settings import MIDDLEWARE_CLASSES
6+
from django.http import HttpResponse
67

78
from ..compat import get_user_model
89
from ..models import get_application_model
@@ -112,3 +113,24 @@ def test_middleware_success(self):
112113
request = self.factory.get("/a-resource", **auth_headers)
113114
m.process_request(request)
114115
self.assertEqual(request.user, self.user)
116+
117+
def test_middleware_response(self):
118+
m = OAuth2TokenMiddleware()
119+
auth_headers = {
120+
'HTTP_AUTHORIZATION': 'Bearer ' + 'tokstr',
121+
}
122+
request = self.factory.get("/a-resource", **auth_headers)
123+
response = HttpResponse()
124+
processed = m.process_response(request, response)
125+
self.assertIs(response, processed)
126+
127+
def test_middleware_response_header(self):
128+
m = OAuth2TokenMiddleware()
129+
auth_headers = {
130+
'HTTP_AUTHORIZATION': 'Bearer ' + 'tokstr',
131+
}
132+
request = self.factory.get("/a-resource", **auth_headers)
133+
response = HttpResponse()
134+
m.process_response(request, response)
135+
self.assertIn('Vary', response)
136+
self.assertIn('Authorization', response['Vary'])

0 commit comments

Comments
 (0)