如何进行不基于用户模型的自定义身份验证

Jac*_*ian 1 python authentication django django-rest-framework

我的身份验证方案需要一些灵活性.通过这种灵活性,我的意思是我不想完全依赖用户模型或任何模型.在伪代码中我想得到这种逻辑:

class MyCustomAuthentication(authentication.BaseAuthentication)
    def authenticate(self, request):
        email = request.META.get('X_EMAIL')
        password = request.META.get('X_PASSWORD')
        # Here I want to connect to my database
        # then make a query and verify if there exists a row that
        # corresponds to email and password
        # If it exists, then authentication is passed
        # if not, then it is not passed

@api_view()
@authentication_classes((MyCustomAuthentication))
def items(request):
    return Response({"message":"Hello world!"})
Run Code Online (Sandbox Code Playgroud)

所以,如你所见,我不想依赖ORM,我只想用自己的友好sql来做自己的整个事业.但我不知道如何以及我应该从认证中返回什么.

RLo*_*ott 5

雅可比,您需要导入@authentication_classes(...)装饰器.要做到这一点,只需在文件顶部添加以下行:

from rest_framework.decorators import authentication_classes
Run Code Online (Sandbox Code Playgroud)

资料来源:http: //www.django-rest-framework.org/api-guide/views/