authentication - How to limit view to authenticated user in Django Rest Framework -
i have django rest framework application. authentication performed through login method:
def login(self, request): user = find_my_user(request) user.backend = 'django.contrib.auth.backends.modelbackend' login(request, user) return response({"status": "ok"})
authentication works fin.
i have viewset having list_route() need authenticated user used. here code:
class commonview(viewsets.viewset): @list_route() @authentication_classes(sessionauthentication) @permission_classes(isauthenticated) def connected(self, request): return response({"status": "ok"})
even if user not authenticated (no session cookie), action performed.
as work around, i've performed :
class commonview(viewsets.viewset): @list_route() def connected(self, request): if request.user.is_authenticated(): return response({"status": "ok"}) else: return response({"status": "ko", "message": "unauthenticated"})
but feel cleaner, idea ?
you can create custom listrouteisauthenticated
permission class inheriting basepermission
class deny permission unauthenticated users request in list
route.
for detail
route requests, allow unrestricted access, regardless of if request authenticated or unauthenticated.
from rest_framework.permissions import basepermission class listrouteisauthenticated(basepermission): """ custom permission class authenticates request `list` route """ def has_permission(self, request, view): if view.action == 'list': return request.user , request.user.is_authenticated() # check user authenticated 'list' route requests return true # no authentication check otherwise
then in viewset, need define permission class.
class commonview(viewsets.viewset): permission_classes = [listrouteisauthenticated] ...
Comments
Post a Comment