2015-10-19 115 views
1

對於下面的一段代碼,我想返回一個布爾值,對應於用戶是否被認證。在Django rest框架中對無效令牌認證的自定義響應

class UserAuthenticatedView(APIView): 
    authentication_classes = (TokenAuthentication,) 
    permission_classes = (AllowAny,) 
    def get(self, request, format=None): 
     is_authenticated = request.user.is_authenticated() 
     resp = {'is_authenticated': is_authenticated} 
     return Response(resp, content_type="application/json", status=status.HTTP_200_OK) 

然而,對於無效令牌,控制甚至不是不打算裏面get方法由於這我不能夠自定義的響應。在這種情況下,我收到了回覆:{'detail': 'invalid token'}, 有關如何自定義無效令牌響應的想法?

+0

我想你應該創建一個自定義TokenAuthentication類。 – Gocht

回答

3

這爲我工作:

自定義身份驗證類:

class MyAuthentication(authentication.TokenAuthentication): 
    def authenticate_credentials(self, key): 
     try: 
      token = self.model.objects.select_related('user').get(key=key) 
     except self.model.DoesNotExist: 
      return (None, '') 

     if not token.user.is_active: 
      raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) 

     return (token.user, token) 

視圖類:

class UserAuthenticatedView(APIView): 
    authentication_classes = (MyAuthentication,) 
    permission_classes = (AllowAny,) 

    def get(self, request, format=None): 
     is_authenticated = False 
     if request.user and request.user.is_authenticated(): 
      is_authenticated = True 
     resp = {'is_authenticated': is_authenticated} 
     return Response(resp, content_type="application/json", status=status.HTTP_200_OK) 
4

您可以創建CustomTokenAuthentication類並覆蓋authenticate_credentials()方法以在無效令牌的情況下返回自定義響應。

class CustomTokenAuthentication(TokenAuthentication): 

    def authenticate_credentials(self, key): 
     try: 
      token = self.model.objects.select_related('user').get(key=key) 
     except self.model.DoesNotExist: 
      # modify the original exception response 
      raise exceptions.AuthenticationFailed('Custom error message') 

     if not token.user.is_active: 
      # can also modify this exception message 
      raise exceptions.AuthenticationFailed('User inactive or deleted') 

     return (token.user, token) 

這樣做了以後,在你的DRF設置或在每個視圖/視圖集中的基礎定義這個定製令牌認證類。

另一種選擇是創建一個custom exception handler.在這種情況下,您可以檢查引發的異常是否爲AuthenticationFailed,異常消息是'invalid token'。在那裏你可以修改異常信息(也可以查看官方DRF example)。