1212class ApiKeyOrGuestAuthentication (ApiKeyAuthentication ):
1313 """Authentication backend that falls back to guest access when no API key is provided."""
1414
15- def _unauthorized (self ):
16- """Allow guests anyway."""
17- # Allow guests anyway
18- return True
19-
2015 def is_authenticated (self , request , ** kwargs ):
2116 """Authenticate via API key, handling custom user model.
2217
@@ -26,19 +21,26 @@ def is_authenticated(self, request, **kwargs):
2621 User = get_user_model () # noqa: N806 - Django convention for user model reference
2722 username_field = User .USERNAME_FIELD
2823
24+ # Note that it's only safe to return 'True'
25+ # in the guest case. If there is an API key supplied
26+ # then we must not return 'True' unless the
27+ # API key is valid.
2928 try :
3029 username , api_key = self .extract_credentials (request )
3130 except ValueError :
32- return self ._unauthorized ()
33-
31+ return True # Allow guests.
3432 if not username or not api_key :
35- return self ._unauthorized ()
33+ return True # Allow guests.
34+
35+ # IMPORTANT: Beyond this point we are no longer
36+ # handling the guest case, so all incorrect usernames
37+ # or credentials MUST return HttpUnauthorized()
3638
3739 try :
3840 lookup_kwargs = {username_field : username }
3941 user = User .objects .get (** lookup_kwargs )
4042 except (User .DoesNotExist , User .MultipleObjectsReturned ):
41- return self . _unauthorized ()
43+ return HttpUnauthorized ()
4244
4345 if not self .check_active (user ):
4446 return False
0 commit comments