简体   繁体   中英

Can I Override Global Authentication for a Single Request Type in an ApiView using DRF?

I'm using django_rest_frameork (DRF) on a large project. In general, I want all my views protected, so I have Token Authentication set as my global authentication scheme. But there are a few views that I want this turned off, for example, creating a new user, and logging in.

For example my /User ApiView has a get and post method. The get returns the user profile and the post creates a new user. How can I override the global authetication scheme on the /User post only? I still need it turned on when getting user information.

I'm asking more to increase my understanding of DRF than anything. I know that I could separate the /User/ calls into to different ApiViews, where one is authenticated and one isn't. I also know that I could dispense with the global scheme entirely and authenticate on a pre-view basis.

Is there a particularly "pythonic" or django-typical way of doing this? Any recommendations?

You can write custom permission class and use it in some views. For example:

from rest_framework.permissions import BasePermission

class AllowPostAny((BasePermission):
    def has_permission(self, request, view):
        if request.method == "POST":
            return True
        return bool(request.user and request.user.is_authenticated)  

You can now use this permission in view:

class ExampleView(APIView):
    permission_classes = [AllowPostAny]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM