📘 DRF 


# Json Web Token 구현하기
$ pip install djangorestframework-simplejwt

Django REST framework simple JWT??

🧩 JWT(JSON Web Token)

 → 표준으로, 당사자 간에 안전하게 정보를 JSON 객체로 전송하는 방법
 →
인증과 권한 부여에 널리 사용됨
 →
서버는 JWT 생성하여 클라이언트에게 전달하고, 클라이언트는 이후 요청 , JWT 포함하여 서버에 사용자 인증을 수행


🧩 pip install djangorestframework-simplejwt

→ DRF 환경에서 JWT 사용하여 인증 시스템을 구축하는 과정을 간소화해 주는 패키지


🧩 기능

  1. JWT 발급 및 갱신 (토큰 기반 인증)
  2. 액세스 토큰(Access Token)과 리프레시 토큰(Refresh Token) 지원
  3. 토큰 블랙리스트 기능 (로그아웃 시 사용 가능)
  4. 커스텀 설정 가능 (토큰 만료 시간, 클레임 추가 등)

🧩  설정

settings.py
# settings.py
INSTALLED_APPS = [
    'rest_framework',
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

# JWT 설정 (옵션)
from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30),  # 액세스 토큰 만료 시간 (30분)
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),  # 리프레시 토큰 만료 시간 (7일)
}

🧩  JWT 토큰 발급 및 인증 API 만들기

토큰 발급 뷰 (urls.py)

Simple JWT는 기본적으로 TokenObtainPairViewTokenRefreshView를 제공

from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,  # 로그인 시 액세스 + 리프레시 토큰 발급
    TokenRefreshView      # 리프레시 토큰을 통해 새로운 액세스 토큰 발급
)

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

🧩  JWT 인증 테스트

서버 실행 후($ python manage.py runserver) Postman

로그인을 수행하여 Token을 받음

 

일정 시간이 지나면 유효하지 않은 토큰이 되기  때문에 재발급이 필요(token/refresh/)

 

curl

1. 로그인하여 토큰 발급

curl -X POST http://127.0.0.1:8000/api/token/ \
     -H "Content-Type: application/json" \
     -d '{"username": "testuser", "password": "testpassword"}'

✅ 응답 예시:

{
    "refresh": "eyJhbGciOiJIUzI1NiIs...",
    "access": "eyJhbGciOiJIUzI1NiIs..."
}

 

2. 액세스 토큰을 사용하여 API 요청

curl -X GET http://127.0.0.1:8000/protected-api/ \
     -H "Authorization: Bearer 액세스_토큰"

 

3. 리프레시 토큰을 사용해 새 액세스 토큰 발급

curl -X POST http://127.0.0.1:8000/api/token/refresh/ \
     -H "Content-Type: application/json" \
     -d '{"refresh": "리프레시_토큰"}'

🧩  JWT를 이용한 인증이 필요한 API 만들기

@authentication_classes@permission_classes를 설정

from rest_framework_simplejwt.authentication import JWTAuthentication

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication

class ProtectedView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({"message": "이 API는 인증된 사용자만 접근 가능합니다!"})

# urls.py에 추가
urlpatterns += [
    path('protected-api/', ProtectedView.as_view(), name='protected_api'),
]

🧩  정리

djangorestframework-simplejwtJWT 기반 인증을 쉽게 적용할 수 있도록 도와주는 Django 라이브러리
TokenObtainPairView, TokenRefreshView 등을 제공하여 로그인 후 JWT 발급 및 갱신을 간단하게 구현 가능.
JWTAuthentication을 사용하여 보호된 API를 만들 수 있음

'🔥 공부 > 📘 DRF 공부' 카테고리의 다른 글

[DRF] serializer_class?  (0) 2025.02.17
[DRF] Generics?  (1) 2025.02.17
[DRF] Django Deploy with AWS, 배포  (0) 2025.02.06
[DRF] 외부 API 연동하기 (feat. ChatGPT)  (0) 2025.02.05
[DRF] API 문서화, DRF-Spectacular  (0) 2025.02.04

🐾Recent posts