pip install djangorestframework-simplejwt
settings.py
simple-jwt ํ๋ ์์ํฌ ์ฌ์ฉ๊ณผ ๊ถํ ๊ด๋ฆฌ๋ฅผ ์ํด settings.py ์์ ๋ค์๊ณผ ๊ฐ์ด ์ถ๊ฐํด์ค๋ค.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
์ปค์คํ ์ ์ ๋ชจ๋ธ์ ์ฌ์ฉ ๋ฐ simple-jwt ์ถ๊ฐ ์ต์ ์ ์ฃผ๊ธฐ ์ํด ๋ค์๋ ์ถ๊ฐํ๋ค.
AUTH_USER_MODEL = "์ฑ์ด๋ฆ.CustomUser" # ์ปค์คํ
์ ์ ๋ชจ๋ธ ์ฌ์ฉ
# simple jwt ์ต์
์ ๊ณต
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
serializers.py
๊ฒฐ๊ณผ ์ปค์คํ ์ ์ํด TokenObtainPairSerializer๋ฅผ ์์๋ฐ์
# jwt token ๊ฒฐ๊ณผ ์ปค์คํ
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
# response ์ปค์คํ
default_error_messages = {
'no_active_account': {'message':'username or password is incorrect!',
'success': False,
'status' : 401}
}
# ์ ํจ์ฑ ๊ฒ์ฌ
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
# response์ ์ถ๊ฐํ๊ณ ์ถ์ key๊ฐ๋ค ์ถ๊ฐ
data['username'] = self.user.username
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['success'] = True
return data
class MyTokenObtainPairView(TokenObtainPairView):
permission_classes = (permissions.AllowAny,)
serializer_class = MyTokenObtainPairSerializer
์ฑ ํด๋ ์์ urls.py ์์ฑ
urlpatterns = [
# ๋ก๊ทธ์ธ (JWT TOKEN)
path('token', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh', TokenRefreshView.as_view(), name='token_refresh'),
path('token/verify', TokenVerifyView.as_view(), name='token_verify'),
]
๊ธฐ์กด urls.py์ ์ฐ๊ฒฐ
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('์ฑ์ด๋ฆ.urls')),
]
[์ถ์ฒ]
https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html
https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html
'BACKEND > Django' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Django MVC ๊ตฌ์กฐ (0) | 2022.05.02 |
---|