【问题标题】:Python Django Rest Framework authenticationPython Django Rest 框架身份验证
【发布时间】:2015-06-15 09:22:09
【问题描述】:

我正在尝试对通过 Web API 接口在 url 中传递的 GUID 进行身份验证。但是,我无法将 GUID 传递给我的 Authenticate 类。

注意:通过身份验证是指确保它是有效的 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',
         )
}
我的客户应用中的

Authenticate 类如下所示:

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

请求看起来像这样:

问题: 我喜欢在 Authenticate 类中检索 GUID 并确保它有效。目前,我不断收到您在屏幕截图中看到的错误,并且我的日志显示:“没有 guid!”

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

谢谢

【问题讨论】:

  • 检查您是否有权访问自己的kwargs。做guid = self.kwargs.get('guid', None)
  • 我查过,authenticate() 中没有 DRF 视图的 kwargs。我已经更新了我的ans。另一种解决方案是在调用时将视图的kwargs 传递给authenticate()

标签: python django authentication django-rest-framework


【解决方案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'/' 来访问 guid 并访问拆分后获得的列表的倒数第三个索引。

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

另一种解决方案是在通过覆盖 DRF 的身份验证过程调用 authenticate() 时,在 DRF 视图中显式传递 kwargs

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2017-11-02
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多