这就是您使用 Django Rest Framework 创建自定义身份验证类的方式。子类BaseAuthentication
化并覆盖该.authenticate(self, request)
方法。
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
class CustomAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
"""
Consider the method validate_access_token() takes an access token,
verify it and return the User.username if the token is valid else None
"""
username = validate_access_token(request.META.get('X_ACCESS_TOKEN'))
if not username:
return None #return None if User is not authenticated.
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise exceptions.AuthenticationFailed('No such user')
return (user, None)
然后更改 DEFAULT_AUTHENTICATION_CLASSES
设置以指向自定义身份验证类
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'api.core.auth.CustomAuthentication',
),
}