rest_framework/request.py中部分认证和权限代码
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
def _not_authenticated(self):
"""
Set authenticator, user & authtoken representing an unauthenticated request.
Defaults are None, AnonymousUser & None.
"""
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER()
else:
self.user = None
认证后将user存储到了request中,为了权限使用时候可以进行判断(红色)
class UserLoginPermission(BasePermission):
def has_permission(self, request, view):
return isinstance(request.user,User)
实例:
authentication.py
from django.core.cache import cache
from rest_framework.authentication import BaseAuthentication
class TokenAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.query_params.get("token")
user = cache.get(token)
if user:
return user ,token
permissions.py
from rest_framework.permissions import BasePermission
from App.models import User
class UserLoginPermission(BasePermission):
def has_permission(self, request, view):
return isinstance(request.user,User)
def has_object_permission(self, request, view, obj):
if obj.b_author.id == request.user.id:
return True