2015-06-15 154 views
1

我正在尝试验证通过Web API接口传递到url中的GUID。不过,我并没有设法通过GUID到我的验证类。Python Django Rest Framework身份验证

注:通过验证我的意思是确保它是一个有效的GUID

urls.py

url(r'^customer_address/(?P<guid>[a-z0-9-]+)/(?P<address_id>[a-z0-9-]+)/$', 
    views.CustomerAddressView.as_view()), 

views.py

class CustomerAddressView(generics.RetrieveAPIView): 
    lookup_field = "address_id"  
    queryset = CustomerAddress.objects.all() 
    serializer_class = CustomerAddressSerializer  

我的settings.py

REST_FRAMEWORK = { 
     'DEFAULT_AUTHENTICATION_CLASSES': (
      'customer.authenticate.Authenticate', 
     ), 
     'DEFAULT_PERMISSION_CLASSES': (
     'rest_framework.permissions.IsAuthenticated', 
     ) 
} 

身份验证类在我的客户应用程序是这样的:

class Authenticate(authentication.BaseAuthentication) : 
    def authenticate(self, request): 

     request = request._request        
     guid = getattr(request, 'guid', None) 


     my_logger.debug(guid) 


     if not guid: 
      my_logger.debug('There is no guid!') 
      return None 


     try: 
      user = Customer.objects.get(guid=guid,brand=1) 
     except Customer.DoesNotExist: 
      raise exceptions.AuthenticationFailed('No such user') 

     return None 

和请求如下:

enter image description here

问题: 我喜欢在clas中检索GUID验证并确保其有效。此刻,我不断收到你在屏幕截图中看到的错误,并且我的日志中显示:'没有guid!

如何将GUID从请求传递到Authenticate类?

感谢

+1

检查你是否可以自己访问'kwargs'。 ''guid = self.kwargs.get('guid',None)' –

+0

我检查过,''authenticate()'中没有DRF视图的'kwargs'。我已经更新了我的答案。另一种解决方案是在调用时将视图的'kwargs'传递给'authenticate()'。 –

回答

1

你可以这样做:

class Authenticate(authentication.BaseAuthentication) : 
    def authenticate(self, request): 

     request = request._request   

     # This is a bit hacky way to get value of guid       
     guid = request.path.split('/')[-3] 

     my_logger.debug(guid) 

     if not guid: 
      my_logger.debug('There is no guid!') 
     return None 

     try: 
      user = Customer.objects.get(guid=guid,brand=1) 
     except Customer.DoesNotExist: 
      raise exceptions.AuthenticationFailed('No such user') 

    return None 

这是一个有点哈克,因为我试图通过拆分request.path'/'访问​​和访问后得到的列表的第三最后一个索引分裂。

我查过,self有权访问我们通常在DRF视图中获得的kwargs,因此我们无法在此处访问kwargs

当重写DRF的认证过程调用authenticate()时,另一种解决方案是在DRF视图中明确传递kwargs