Django 프로젝트에서 JWT 사용하기
django restframework 를 사용하면서 로그인/회원가입 등의 인증 기능을 간편하게 사용하기 위해서
reat-auth 라이브러리를 사용한다
설치
#> pip3 install django-rest-auth
Installed Apps 에 추가
INSTALLED_APPS = ( ..., 'rest_framework', 'rest_framework.authtoken', => JWT를 사용하지만, 에러가 나지않도록 작성해준다 'rest_auth')
urls.py 추가
urlpatterns = [ ..., url(r'^rest-auth/', include('rest_auth.urls'))]
Migrate
#> python manage.py migrate
Rest-auth를 통한 회원가입
#> pip3 install django-allauth
회원가입 api을 사용하기 위해서 allauth를 설치해준다
Installed Apps에 추가
INSTALLED_APPS = ( ..., 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration',)
allauth를 사용하기 위해서 django.contrib.site 앱을 추가해주고,
allauth관련 앱들을 추가해 준 후에 rest_auth.registration을 추가해준다
SITE_ID = 1 설정
settings.py에 SITE_ID = 1 을 추가해준다.
이는 django.contrib.site 설정 후 마이그레이션 때 django_site라는 테이블이 생성된다.
이 테이블은 domain 과 name 필드를 가지는데 이 테이블에 localhost 데이터가 존재하지 않아서
로컬에서 실행하면 에러가 나게된다. 그래서 SITE_ID = 1 설정을 통해서 localhost로 동작을 가능하게 해준다
어드민 페이지의 site모델에 localhost를 추가해주면 SITE_ID 설정이 없어도 동작한다.
urls.py 추가
urlpatterns = [ ..., url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))]
이제 JWT를 사용하기위한 설정을 한다
일단 JWT 라이브러리를 지원하는 djangorestframework-jwt를 설치한다
#> pip3 install djangorestframework-jwt
settings.py에 설정 추가
REST_USE_JWT = True
설정이 다 끝났다.
rest-auth 도큐먼트를 보면 사용 가능한 많은 api들을 소개한다
예를 들어서 /rest-auth/login/ 을 해보면
다음과 같이 username과 password를 전달하면 jwt토큰을 응답으로 보내준다.
이를 통해서 jwt을 수행 할 수 있다.
댓글
댓글 쓰기