DRF自定义认证后端在无需认证的路径上仍被执行的问题求助
DRF自定义认证后端在无需认证的路径上仍被执行的问题求助
大家好,我刚接触Django,现在正尝试在项目中集成DRF的权限控制。但自从我在Django的settings.py里配置了REST_FRAMEWORK的DEFAULT_AUTHENTICATION_CLASSES之后,不管我给视图设置什么权限,所有请求都会先触发我自定义认证后端里的authenticate方法,之后才会进入视图处理。这和我理解的不一样,我以为如果视图用了AllowAny权限类,认证方法根本就不会被调用才对。
我的settings.py里的配置是这样的:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'authentication.customauth.CustomAuthBackend', ] }
这是我写的authentication.customauth.CustomAuthBackend类:
class CustomAuthBackend(BaseAuthentication): def authenticate(self, request): user = AuthUtils.get_user_from_token(request) if user is None: raise AuthenticationFailed('User not found') request.user = user return user, None @staticmethod def authenticate_with_password(request): email = request.data.get('email') role = "CONSUMER" if request.data.get('role') is None else request.data.get('role') password = request.data.get('password') user = User.objects.filter(email=email, role=role).first() if password is not None and user is not None and user.check_password(password): return user
那些本该不需要认证就能访问的视图,我都加了@permission_classes([AllowAny])装饰器,比如这个登录视图:
@api_view(['POST']) @permission_classes([AllowAny]) def login(request): user = request.user if user and user.is_active: serializer = UserSerializer(user) tokens_map = AuthUtils.generate_token(request=request, user=user) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND)
按照我的理解,当视图使用rest_framework.permissions.AllowAny权限类时,认证后端的authenticate方法应该不会被执行才对,但现在不管什么请求都先跑一遍认证逻辑,这让我的登录接口都没法正常工作了,有没有大佬能帮我看看问题出在哪?
备注:内容来源于stack exchange,提问作者suvodipMondal
相关产品推荐
相关产品推荐

