Python Django Rest 框架身份验证

标签 python django authentication django-rest-framework

我正在尝试验证通过 Web API 接口(interface)在 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',
         )
}
我的客户应用程序中的

身份验证类如下所示:

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

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

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

谢谢

最佳答案

你可以这样做:

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

这有点 hacky,因为我试图通过拆分关于 '/'request.path 来访问 guid 并访问第三个 -分割后获得的列表的最后一个索引。

我已经检查过,self 无法访问我们通常在 DRF View 中获取的 kwargs,因此我们无法访问 kwargs这里。

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

关于Python Django Rest 框架身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30841580/

相关文章:

python - 为什么类属性不记住通过 __iadd__ 方法添加的值?

macos - 为 OSX 编写可插入身份验证模块 (PAM)

php - Symfony2 的 AccessDeniedHandlerInterface 自动重定向未经授权的用户

带有 Docker 身份验证的 MongoDB

python - 为什么python中的计算机之间的强制转换规则不同?

python - 使用 python 在 chrome 中打开 .pdf 文档

python - 在 Python 3.6 中运行时根据 Union 类型检查变量

python - 使用 Django Uploadify S3 接收 HTTP 错误

Django - 生成默认 slug

jquery - django-autocomplete-light : "The results could not be loaded"