Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

对同一 viewset 的不同 action 方法不同的 authenticaltion 是否可行?

大佬们,我有一个需求就是我有一个 viewset 我想使用 post 方法的时候使用 JWT 认证,而使用 list 和 retrieve 方法的时候不使用认证,各位老哥有办法吗?我用过 @[authentication_class]()这个装饰器,但是无效啊,有没有大佬能解答下

class UserViewSet(CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    queryset = UserProfile.objects.all()
    #authentication_classes = [JwtAuthorizationAuthentication,]

    def get_serializer_class(self):
        if self.action == 'create':
            return UserRegisterSerializer
        else:
            return UserLoginSerializer

    def create(self, request, *args, **kwargs):
        return Response('ok')

    def retrieve(self, request, *args, **kwargs):
        print(f'1{self.authentication_classes}')
        return Response('ok')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这个需要重写 get_authenticators 方法,因为视图在顶层已经做了认证类的计算处理,在 get_authenticators 方法中,根据请求的方法,判断返回不同的认证类

def get_authenticators(self):
    # 伪代码
    if is_post_method(post):
        return [JwtAuthorizationAuthentication,]
    return super().get_authenticators()

具体可以翻阅 DRF views.py 源码


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...