2015-10-19 112 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)。