DRF with JWT

JWT ๋กœ ์ธ์ฆํ•˜๊ธฐ!

I. ์ค€๋น„์‚ฌํ•ญ

1. REST framework JWT Auth ํŒจํ‚ค์ง€ ์„ค์น˜

pip install djangorestframework-jwt

2. settings.py ์„ค์ • ๋ณ€๊ฒฝ

(1) REST_FRAMEWORK ์„ค์ • ๋ณ€๊ฒฝ

  • REST_FRAMEWORK ์„ค์ • ๋ณ€์ˆ˜ ์•„๋ž˜์˜ ๋‚ด์šฉ ์ถ”๊ฐ€

  • authentication ๋ฐฉ์‹์„ JSONWebTokenAuthentication ๋ฐฉ์‹์œผ๋กœ ์„ค์ •ํ•˜๊ฒ ๋‹ค๋Š” ์˜๋ฏธ

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # Token ์—์„œ ๊ต์ฒด
        # 'rest_framework.authentication.TokenAuthentication',
    ]
}

(2) REST_USE_JWT ์„ค์ • ์ถ”๊ฐ€

  • DRF auth๊ฐ€ JWT๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ์„ค์ • ์ถ”๊ฐ€

REST_USE_JWT = True

(3) JWT_AUTH ์„ค์ • ์ถ”๊ฐ€

import datetime
JWT_AUTH = {
    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_ALGORITHM': 'HS256',
    'JWT_ALLOW_REFRESH': True,
  # 1์ฃผ์ผ๊ฐ„ ์œ ํšจํ•œ ํ† ํฐ
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
  # 28์ผ ๋งˆ๋‹ค ๊ฐฑ์‹ ๋จ(์œ ํšจ ๊ธฐ๊ฐ„ ์—ฐ์žฅ์‹œ)
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=28),
}

II. ๋ชจ๋“  ๋ณ€๊ฒฝ์‚ฌํ•ญ

settings.py

# DRF auth settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # Token ์—์„œ ๊ต์ฒด
        # 'rest_framework.authentication.TokenAuthentication',
    ]
}

# DRF auth๊ฐ€ JWT๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ํ•˜๋Š” ์„ค์ •
REST_USE_JWT = True

# JWT Token ๊ด€๋ จ ์ •๋ณด ์„ค์ •: ์–ด๋–ค ์ •๋ณด๋ฅผ ๋‹ด์•„ ๋ณด๋‚ผ์ง€
import datetime
JWT_AUTH = {
    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_ALGORITHM': 'HS256',
    'JWT_ALLOW_REFRESH': True,
  # 1์ฃผ์ผ๊ฐ„ ์œ ํšจํ•œ ํ† ํฐ
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
  # 28์ผ ๋งˆ๋‹ค ๊ฐฑ์‹ ๋จ(์œ ํšจ ๊ธฐ๊ฐ„ ์—ฐ์žฅ์‹œ)
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=28),
}

โ€‹```

Last updated