说明
from rest_framework.authentication import BaseAuthentication class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ 用户认证,如果验证成功后返回元组: (用户,用户Token) :param request: :return: return1:(user,token)表示验证通过并设置用户名和Token; return2:AuthenticationFailed异常 return3:None,表示跳过该验证; 如果跳过了所有认证,默认用户和Token和使用配置文件进行设置 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() # 默认值为:匿名用户 else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN()# 默认值为:None else: self.auth = None """ ....return ('登录用户', '用户token') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass
局部认证
在需要认证的视图类里加上authentication_classes = [认证组件1类名,认证组件2类名....]
示例如下:
seralizers.py
|
1
2
3
4
5
6
7
|
from rest_framework import serializers
from app01 import models
class PublishSerializers(serializers.ModelSerializer):
class Meta:
model = models.Publish
fields = '__all__'
|
auth.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from app01 import models
class TokenAuth(BaseAuthentication):
def authenticate(self,request):
'''函数名必须叫authenticate'''
# 验证条件根据需求设置(此示例为需要有token值)
token = request.GET.get('token')
token_obj = models.Token.objects.filter(token=token).first()
if not token_obj:
# 如果验证失败,需要跑出AuthenticationFailed错误
raise exceptions.AuthenticationFailed("验证失败!")
else:
user = token_obj.user
# 如果验证成功,需要返回一个元组,分别是用户以及验证类的实例对象,然后内部会赋值给request.user和request.auth
return user.username,token_obj
|
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from app01 import models class BlackNameAuth(BaseAuthentication): '''黑名单认证''' def authenticate(self, request): BLACK_NAME_LIST = ['小花', '小翠'] # 通过从url获取user_id的方式模拟用户登录 user_id = request.GET.get('uid') user = models.UserInfo.objects.filter(pk=user_id).first() if not user or user.username in BLACK_NAME_LIST: raise AuthenticationFailed('您没有登录或者被关小黑屋啦') else: return user.username,user_id