Skip to content

Commit 9b1a5f9

Browse files
author
Massimiliano Pippi
committed
oauth2 authentication backend and middleware
1 parent 3ebc230 commit 9b1a5f9

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

oauth2_provider/backends.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from django.contrib.auth import get_user_model
2+
3+
from .oauth2_backends import get_oauthlib_core
4+
5+
UserModel = get_user_model()
6+
OAuthLibCore = get_oauthlib_core()
7+
8+
9+
class OAuth2Backend(object):
10+
"""
11+
Authenticate against an OAuth2 access token
12+
"""
13+
14+
def authenticate(self, **credentials):
15+
request = credentials.get('request')
16+
if request is not None:
17+
oauthlib_core = get_oauthlib_core()
18+
valid, r = oauthlib_core.verify_request(request, scopes=[])
19+
if valid:
20+
return r.user
21+
return None
22+
23+
def get_user(self, user_id):
24+
try:
25+
return UserModel.objects.get(pk=user_id)
26+
except UserModel.DoesNotExist:
27+
return None

oauth2_provider/middleware.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from django.contrib.auth import authenticate
2+
3+
4+
class OAuth2TokenMiddleware(object):
5+
"""
6+
Middleware for OAuth2 user authentication
7+
8+
This middleware is able to work along with AuthenticationMiddleware and its behaviour depends
9+
on the order it's processed with.
10+
11+
If it comes *after* AuthenticationMiddleware and request.user is valid, leave it as is and does
12+
not proceed with token validation. If request.user is the Anonymous user proceeds and try to
13+
authenticate the user using the OAuth2 access token.
14+
15+
If it comes *before* AuthenticationMiddleware, or AuthenticationMiddleware is not used at all,
16+
tries to authenticate user with the OAuth2 access token and set request.user field. Setting
17+
also request._cached_user field makes AuthenticationMiddleware use that instead of the one from
18+
the session.
19+
"""
20+
def process_request(self, request):
21+
# do something only if request contains a Bearer token
22+
if request.META.get('HTTP_AUTHORIZATION', '').startswith('Bearer'):
23+
if not hasattr(request, 'user') or request.user.is_anonymous():
24+
user = authenticate(request=request)
25+
if user:
26+
request.user = request._cached_user = user

0 commit comments

Comments
 (0)