본문 바로가기
TIL/Python | Django

2021.8.7 TIL : [Django] DRF 3 - authentication

by yeon_zoo 2021. 8. 7.

사용자가 로그인하고 서버에 요청을 할 때 로그인해서 권한이 있는지 확인하는 데 authentication이 필요하다.

BasicAuthentication

우리가 지난 글에서 작성했던 내용들은 HTTP basic authentication으로 클라이언트에게 아이디와 비밀번호만을 요청한다. 장고 rest framework 공식 문서를 확인하면 이 basic auth는 테스트 목적으로만 사용하는 것이 적절하다. 만약 이 auth 방법을 실제 프로덕트에서 사용하고 싶다면 https 를 통해서만 가능하게 하고 매번 아이디와 비밀번호를 물어보게 해야 한다. 

SessionAuthentication

장고의 기본 authentication 세션 백엔드를 사용한다. 이는 웹사이트와 동일한 세션 컨텍스트에서 실행되는 AJAX 클라이언트에 적합하다. 

SessionAuthentication을 이용하는 방법을 알아볼 것이다. 일단 강의에서 진행한 대로 class-based views에 대해서 진행하는 방법을 알아볼 것인데, django rest framework 공식 문서를 보면 generic class 나 function based view에서 진행하는 방법도 나와 있으니 참고해 보면 좋다. 

views.py 에 다음 내용들로 업데이트 한다. 

...
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated

# Create your views here.

class GenericAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

    lookup_field = 'id'
    authentication_classes = [SessionAuthentication, BasicAuthentication] 
    #만약 가능한 session authentication이 없다면 basic authentication을 사용한다는 뜻
    permission_classes = [IsAuthenticated]
    def get(self, request, id = None):
        if id:
            return self.retrieve(request)
        else:
            return self.list(request)
    def post(self, request):
        return self.create(request)
    def put (self, request, id=None):
        return self.update(request, id)
    def delete(self, request, id): 
        return self.destroy(request, id)

이렇게 하고 서버에서 로그아웃한 후 접근하려고 하면 다음과 같은 화면이 나온다. 

postman 에서도 비슷한 결과를 확인할 수 있다. 

postman에서는 basic auth를 이용해서  로그인한 후에 접근하면 데이터를 확인할 수 있다. 


TokenAuthentication

이 authentication 스키마는 클라이언트-서버 모델의 초기 설정에 어울리는 스키마로 데스크탑 앱이나 모바일 클라이언트(앱)에서 주로 사용하는 간단한 토큰 기반 HTTP authentication 이다. 토큰 인증을 사용하기 위해서는 데이터베이스에 토큰을 저장해야 하므로 관련 테이블을 만들어야 한다. 이를 위해서 먼저 settings.py에 앱을 추가하고 migrate 해주어야 한다.

INSTALLED_APPS = [
    ...
    'rest_framework.authtoken',
]

migrate를 하고 나면 authtoken이 적용된 것을 확인할 수 있고, admin 사이트에 접속하면 token 테이블이 생성된 것도 볼 수 있다. 일단 우리는 admin 사이트에서 수동으로 전에 만들었던 superuser에 대해서 token을 만들어 준다. 

그리고 나서 postman에서 get으로 generic/article/1에 정보를 요청해보면 "Authentication credentials were not provided." 이라는 문구와 함께 접근할 수 없는 것을 알 수 있다. 이 때 Header에서 Key에는 Authentication을, Value에는 Token <token 내용> 을 넣어주면 api 내용을 확인할 수 있다. (이 때 주의해야 할 점은 아까 Authorization 탭에서 Basic Auth를 선택했던 것을 유지하고 있으면 에러가 날 것이다. 우리는 Basic Auth가 아닌 토큰을 이용하고 있으니 다시 원상태인 Inherit auth from parent를 선택해줘야 한다.)

이렇게 대략적인 인증 방법에 대해 배워볼 수 있었다! 다음은 view sets & router에 대한 내용이다. 

댓글