Django:rest 프레임워크 인증 (authentication)

14165 단어
  • 사용자 URL이 전송한token 인증
  • from django.conf.urls import url, include
    from web.viewsimport TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
    urls.py
    
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class TestAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER()
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            #      ,      WWW-Authenticate    
            pass
    
    
    class TestView(APIView):
        authentication_classes = [TestAuthentication, ]
        permission_classes = []
    
        def get(self, request, *args, **kwargs):
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    
    views.py
    
  • 헤드 인증 요청
  • from django.conf.urls import url, include
    from web.viewsimport TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
    urls.py
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class TestAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER()
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            import base64
            auth = request.META.get('HTTP_AUTHORIZATION', b'')
            if auth:
                auth = auth.encode('utf-8')
            auth = auth.split()
            if not auth or auth[0].lower() != b'basic':
                raise exceptions.AuthenticationFailed('    ')
            if len(auth) != 2:
                raise exceptions.AuthenticationFailed('    ')
            username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':')
            if username == 'alex' and password == '123':
                return ('    ', '  token')
            else:
                raise exceptions.AuthenticationFailed('        ')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            return 'Basic realm=api'
    
    
    class TestView(APIView):
        authentication_classes = [TestAuthentication, ]
        permission_classes = []
    
        def get(self, request, *args, **kwargs):
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    
    views.py
    
  • 다중 인증 규칙
  • from django.conf.urls import url, include
    from web.views.s2_auth import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
    urls.py
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class Test1Authentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
    
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            import base64
            auth = request.META.get('HTTP_AUTHORIZATION', b'')
            if auth:
                auth = auth.encode('utf-8')
            else:
                return None
            print(auth,'xxxx')
            auth = auth.split()
            if not auth or auth[0].lower() != b'basic':
                raise exceptions.AuthenticationFailed('    ')
            if len(auth) != 2:
                raise exceptions.AuthenticationFailed('    ')
            username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':')
            if username == 'alex' and password == '123':
                return ('    ', '  token')
            else:
                raise exceptions.AuthenticationFailed('        ')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            # return 'Basic realm=api'
            pass
    
    class Test2Authentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            pass
    
    
    class TestView(APIView):
        authentication_classes = [Test1Authentication, Test2Authentication]
        permission_classes = []
    
        def get(self, request, *args, **kwargs):
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    
    views.py
    
  • 인증 및 권한
  • from django.conf.urls import url, include
    from web.views import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
    urls.py
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import BaseAuthentication
    from rest_framework.permissions import BasePermission
    
    from rest_framework.request import Request
    from rest_framework import exceptions
    
    token_list = [
        'sfsfss123kuf3j123',
        'asijnfowerkkf9812',
    ]
    
    
    class TestAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """
                ,           : (  ,  Token)
            :param request: 
            :return: 
                None,       ;
                             ,     Token           
                    self._authenticator = None
                    if api_settings.UNAUTHENTICATED_USER:
                        self.user = api_settings.UNAUTHENTICATED_USER() #     :    
                    else:
                        self.user = None
            
                    if api_settings.UNAUTHENTICATED_TOKEN:
                        self.auth = api_settings.UNAUTHENTICATED_TOKEN()#     :None
                    else:
                        self.auth = None
                (user,token)             Token;
                AuthenticationFailed  
            """
            val = request.query_params.get('token')
            if val not in token_list:
                raise exceptions.AuthenticationFailed("      ")
    
            return ('    ', '  token')
    
        def authenticate_header(self, request):
            """
            Return a string to be used as the value of the `WWW-Authenticate`
            header in a `401 Unauthenticated` response, or `None` if the
            authentication scheme should return `403 Permission Denied` responses.
            """
            pass
    
    
    class TestPermission(BasePermission):
        message = "      "
    
        def has_permission(self, request, view):
            """
                         
            Return `True` if permission is granted, `False` otherwise.
            :param request: 
            :param view: 
            :return: True   ;False   
            """
            if request.user == "   ":
                return True
    
        # GenericAPIView get_object   
        def has_object_permission(self, request, view, obj):
            """
                GenericAPIView,      get_object      ,          
            Return `True` if permission is granted, `False` otherwise.
            :param request: 
            :param view: 
            :param obj: 
            :return: True   ;False   
            """
            if request.user == "   ":
                return True
    
    
    class TestView(APIView):
        #        request.user  
        authentication_classes = [TestAuthentication, ]
    
        #   
        #          
        permission_classes = [TestPermission, ]
    
        def get(self, request, *args, **kwargs):
            # self.dispatch
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    
    views.py
    
  • 전역에서 상기 조작을 사용하여 단독 보기를 특수하게 설정하고 전역을 설정하려면 파일에 쓰면 된다.
  • REST_FRAMEWORK = {
        'UNAUTHENTICATED_USER': None,
        'UNAUTHENTICATED_TOKEN': None,
        "DEFAULT_AUTHENTICATION_CLASSES": [
            "web.utils.TestAuthentication",
        ],
        "DEFAULT_PERMISSION_CLASSES": [
            "web.utils.TestPermission",
        ],
    }
    
    settings.py
    
    from django.conf.urls import url, include
    from web.views import TestView
    
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]
    
    urls.py
    
    # -*- coding:utf-8 -*-
    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class TestView(APIView):
    
        def get(self, request, *args, **kwargs):
            # self.dispatch
            print(request.user)
            print(request.auth)
            return Response('GET  ,    ')
    
        def post(self, request, *args, **kwargs):
            return Response('POST  ,    ')
    
        def put(self, request, *args, **kwargs):
            return Response('PUT  ,    ')
    
    views.py
    

    이전 장: Django:rest 프레임워크 프레임워크 다음 장: Django:rest 프레임워크의 흐름 제한 (throttle)

    좋은 웹페이지 즐겨찾기