2015-09-29 25 views
8

http://www.django-rest-framework.org/api-guide/authentication/#custom-authenticationXác thực tùy chỉnh khung Django Rest

Tôi muốn sử dụng xác thực tùy chỉnh trong ứng dụng django của mình nhưng không thể tìm cách áp dụng điều này. có ai co thể giúp tôi với điều này không. Ví dụ là rõ ràng với tôi được đưa ra trong tài liệu, nhưng họ đã không đề cập đến nơi để tạo ra lớp mới này và làm thế nào để sử dụng này.

Cảm ơn trước!

Trả lời

0

Trong thư mục chứa tệp api của bạn, hãy tạo tệp khác để giữ lớp xác thực tùy chỉnh của bạn, chẳng hạn như authentication.py. Sau đó, trong cài đặt của bạn, dưới DEFAULT_AUTHENTICATION_CLASSES, trỏ đến lớp xác thực tùy chỉnh của bạn.

8

Cách triển khai lược đồ xác thực tùy chỉnh trong DRF?

Để triển khai giao thức xác thực tùy chỉnh, chúng tôi cần phân lớp lớp DRF's BaseAuthentication và ghi đè phương thức .authenticate(self, request).

Phương thức sẽ trả về hai bộ gồm (user, auth) nếu xác thực thành công hoặc None nếu không. Trong một số trường hợp, chúng tôi có thể nêu một ngoại lệ AuthenticationFailed từ phương thức .authenticate().

Ví dụ (từ DRF docs):

phép nói rằng chúng tôi muốn xác nhận bất cứ yêu cầu đến như là người dùng được đưa ra bởi username trong một tiêu đề yêu cầu tùy chỉnh tên 'X_USERNAME'.

Bước 1: Tạo lớp xác thực Tuỳ chỉnh

Để làm điều đó, chúng ta sẽ tạo một tập tin authentication.py trong 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 

Bước 2: Xác định lớp xác thực tùy chỉnh

Sau khi tạo lớp thẩm định tùy chỉnh, chúng ta cần phải xác định lớp xác thực này trong cài đặt DRF của chúng tôi. Làm điều này, tất cả các yêu cầu sẽ được xác thực dựa trên lược đồ xác thực này.

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

Lưu ý: Nếu bạn muốn sử dụng này lớp xác thực tùy chỉnh trên cơ sở per-view hoặc mỗi viewset cơ sở và không phải trên cấp độ toàn cầu, bạn có thể định nghĩa lớp xác thực này một cách rõ ràng trong quan điểm của bạn.

class MyView(APIView): 

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

    ... 
+0

bạn có thể xin vui lòng cho một ví dụ về cách sử dụng này sử dụng curl? – momokjaaaaa

+1

@momokjaaaaa Kiểm tra liên kết SO này để gửi tiêu đề trong yêu cầu POST. http://stackoverflow.com/questions/356705/how-to-send-a-header-using-a-http-request-through-a-curl-call –

3

Dưới đây là một ví dụ đơn giản có thể được sử dụng để đạt được xác thực tùy chỉnh. Trong ví dụ để truy cập điểm cuối, bạn phải chuyển tên người dùng & mật khẩu trên dữ liệu POST.

urls.py

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

quan điểm.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' 
Các vấn đề liên quan