2015-09-29 10 views

Odpowiedz

0

W folderze zawierającym pliki api utwórz inny plik, w którym będzie przechowywana niestandardowa klasa uwierzytelniania, na przykład authentication.py. Następnie w ustawieniach pod numerem DEFAULT_AUTHENTICATION_CLASSES wskaż niestandardową klasę uwierzytelniania.

8

Jak zaimplementować niestandardowy schemat uwierzytelniania w DRF?

Aby zaimplementować niestandardowy schemat uwierzytelniania, musimy podklasować klasę DRF o numerze BaseAuthentication i zastąpić metodę .authenticate(self, request).

Metoda powinna zwrócić dwóm krotkom (user, auth), jeśli uwierzytelnienie się powiedzie, lub None w przeciwnym razie. W niektórych okolicznościach możemy podnieść wyjątek AuthenticationFailed z metody .authenticate().

Przykład (z DRF docs):

Powiedzmy chcemy dokonać uwierzytelnienia przychodzące żądanie jako użytkownik danego przez username w nagłówku żądania zwyczaj nazwie 'X_USERNAME'.

Krok 1: Utwórz klasę uwierzytelniania niestandardowy

Aby to zrobić, będziemy tworzyć plik authentication.py w 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 

Krok 2: Określ klasę uwierzytelniania zwyczaj

Po utworzeniu klasy niestandardowego uwierzytelniania, musimy zdefiniować tę klasę uwierzytelniania w naszych ustawieniach DRF. W ten sposób wszystkie żądania będą uwierzytelniane w oparciu o ten schemat uwierzytelniania.

'DEFAULT_AUTHENTICATION_CLASSES': (  
    'my_app.authentication.ExampleAuthentication', # custom authentication class 
    ... 
), 

Uwaga: Jeśli chcesz korzystać z tej klasy niestandardowego uwierzytelniania na podstawie per-view lub per-viewset podstawie, a nie na poziomie globalnym, można zdefiniować tę klasę uwierzytelniania wyraźnie w swoich poglądów.

class MyView(APIView): 

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

    ... 
+0

można proszę podać przykład, w jaki sposób korzystać z tego za pomocą curl? – momokjaaaaa

+1

@momokjaaaaa Zaznacz to łącze SO, aby wysyłać nagłówki w żądaniu POST. http://stackoverflow.com/questions/356705/how-to-send-a-header-using-a-http-request-through-a-curl-call –

3

Osłona jest prostym przykładem, który można wykorzystać do uzyskania niestandardowego uwierzytelnienia. W przykładzie dostępu do punktu końcowego musisz podać nazwę użytkownika & hasło na danych POST.

urls.py

urlpatterns = [ 
    url(r'^stuff/', views.MyView.as_view()), 
    ... 
] 

widoki.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) 

Curl

curl -v -X POST http://localhost:8000/stuff/ -d 'username=my_username&password=my_password' 
Powiązane problemy