# 설치
pip install djangorestframework-simplejwt
# django settings.py
#JWT
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
REST_USE_JWT = True
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(hours=2),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'TOKEN_USER_CLASS': 'users.User',
}
#serializer.py
from .models import User
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
from .models import User
from .serializer import SignupSirializer, SigninSirializer
from rest_framework import generics, status
from rest_framework.response import Response
class SignupView(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = SignupSirializer
class SignupSirializer(serializers.ModelSerializer):
email = serializers.EmailField(
required = True,
),
password = serializers.CharField(
required=True,
write_only = True,
)
password2 = serializers.CharField(write_only = True, required=True)
class Meta:
model = User
fields = ('email','password','password2','username')
def validate(self, data):
if data['password'] != data['password2']:
raise serializers.ValidationError({
"password" : "Pass word fields didn't match"
})
return data
def create(self, validated_data):
user = User.objects.create(
username = validated_data['username'],
email = validated_data['email']
)
token = RefreshToken.for_user(user)
user.set_password(validated_data['password'])
user.refreshtoken = token
user.save()
return user
#views.py
from .models import User
from .serializer import SignupSirializer, SigninSirializer
from rest_framework import generics, status
from rest_framework.response import Response
class SignupView(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = SignupSirializer
#urls.py
from django.urls import path
from .views import SignupView
urlpatterns = [
path('signup/', SignupView.as_view()),
]
결과
정상적으로 로그인 화면이 나오는 것을 확인할수있다.
회원가입 요청 정보를 적고 포스트를 누른다면
201created 및 이메일과 유저 이름이 리턴 된다
자동으로 비밀번호가 암호화 되었으며 옆에 잘려서 안보이지만 리프레시 토큰 또한 잘 들어오는것을 확인할수있다.
비밀번호는 자동으로 pbkdf2 형식으로 암호화 되는듯 하다. 이부분은 추후에 다시 확인해보도록 하자