1. 程式人生 > >restframwork組件的權限認證

restframwork組件的權限認證

rgs serial 邏輯 view elf 視圖 mode fail 權限認證

在一個視圖類下重寫 authentication_classes = [TokenAuth,]然後去認證類TokenAuth裏面實現認證邏輯代碼

認證類代碼塊:

1 class TokenAuth(BaseAuthentication):
2     def authenticate(self,request):
3         token=request.GET.get("token")
4         token_obj=Token.objects.filter(token=token).first()
5         if not token_obj:
6             raise
exceptions.AuthenticationFailed("用戶驗證失敗,500") 7 else: 8 return token_obj.user,token_obj.token

可以繼承基類object,但是需要重寫兩個方法authenticate和authenticate_header

from rest_framework.authentication import BaseAuthentication 導入模板類便於繼承

直接繼承 BaseAuthentication 可以只重寫前面一個

視圖類代碼塊:

 1 class BookShow(viewsets.ModelViewSet):
2 authentication_classes = [TokenAuth,] 3 4 queryset = Book.objects.all() 5 serializer_class = BookModelSerializers 6 def list(self, request, *args, **kwargs): 7 print(request.user) 8 print(request.auth) 9 book_list=Book.objects.all() 10 bs=BookModelSerializers(book_list,many=True,context={"
request":request}) 11 return Response(bs.data)

restframwork組件的權限認證