Django Rest Framework自定义身份验证

Arb*_*zvi 12 python authentication django rest django-rest-framework

http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication

我想在我的django应用程序中使用自定义身份验证,但无法找到如何应用它.任何人都可以帮我这个.我在文档中给出的示例很清楚,但他们没有提到创建这个新类的位置以及如何使用它.

提前致谢!

Rah*_*pta 14

如何在DRF中实现自定义身份验证方案?

要实现自定义身份验证方案,我们需要子类化DRF的BaseAuthentication类并覆盖该.authenticate(self, request)方法.

(user, auth)如果身份验证成功,则该方法应返回两元组,None否则返回.在某些情况下,我们可能会AuthenticationFailed从该.authenticate()方法中引发异常.

示例(来自DRF文档):

让我们说我们想要验证任何传入的请求,因为用户username在名为的自定义请求标头中给出了该请求'X_USERNAME'.

步骤1:创建自定义身份验证类

为此,我们将在中创建一个authentication.py文件my_app.

# my_app/authentication.py
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        username = request.META.get('X_USERNAME') # get the username request header
        if not username: # no username passed in request headers
            return None # authentication did not succeed

        try:
            user = User.objects.get(username=username) # get the user
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user') # raise exception if user does not exist 

        return (user, None) # authentication successful
Run Code Online (Sandbox Code Playgroud)

步骤2:指定自定义身份验证类

创建自定义身份验证类后,我们需要在DRF设置中定义此身份验证类.执行此操作,将根据此身份验证方案对所有请求进行身份验证.

'DEFAULT_AUTHENTICATION_CLASSES': (       
    'my_app.authentication.ExampleAuthentication', # custom authentication class
    ...
),
Run Code Online (Sandbox Code Playgroud)

注意:如果要基于每个视图或每个视图集而不是全局级别使用此自定义身份验证类,则可以在视图中显式定义此身份验证类.

class MyView(APIView):

    authentication_classes = (ExampleAuthentication,) # specify this authentication class in your view

    ...
Run Code Online (Sandbox Code Playgroud)

  • @momokjaaaaa选中此SO链接以在POST请求中发送标头。http://stackoverflow.com/questions/356705/how-to-send-a-header-using-a-http-request-through-a-curl-call (2认同)

Sli*_*eam 6

下面是一个可用于实现自定义身份验证的简单示例.要访问端点,您必须在POST数据上传递用户名和密码.

urls.py

urlpatterns = [
    url(r'^stuff/', views.MyView.as_view()),
    ...
]
Run Code Online (Sandbox Code Playgroud)

views.py

    from django.contrib.auth.models import User
    from rest_framework import viewsets
    from rest_framework.response import Response
    from rest_framework.views import APIView    
    from rest_framework.permissions import IsAuthenticated
    from rest_framework import exceptions
    from rest_framework import authentication
    from django.contrib.auth import authenticate, get_user_model
    from rest_framework.authentication import BasicAuthentication, 
SessionAuthentication


class ExampleAuthentication(authentication.BaseAuthentication):

    def authenticate(self, request):

        # Get the username and password
        username = request.data.get('username', None)
        password = request.data.get('password', None)

        if not username or not password:
            raise exceptions.AuthenticationFailed(_('No credentials provided.'))

        credentials = {
            get_user_model().USERNAME_FIELD: username,
            'password': password
        }

        user = authenticate(**credentials)

        if user is None:
            raise exceptions.AuthenticationFailed(_('Invalid username/password.'))

        if not user.is_active:
            raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))


    return (user, None)  # authentication successful


class MyView(APIView):
    authentication_classes = (SessionAuthentication, ExampleAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, format=None):    
        content = {
            'user': unicode(request.user),
            'auth': unicode(request.auth),  # None
        }
        return Response(content)
Run Code Online (Sandbox Code Playgroud)

卷曲

curl -v -X POST http://localhost:8000/stuff/ -d 'username=my_username&password=my_password'
Run Code Online (Sandbox Code Playgroud)


mca*_*tle 0

在保存 api 文件的文件夹中,创建另一个文件来保存自定义身份验证类,例如authentication.py. 然后在您的设置中的DEFAULT_AUTHENTICATION_CLASSES下,指向您的自定义身份验证类。