티스토리 뷰
Django REST Framework에서 JWT Token 설정 및 API 호출하기
4OurFuture 2025. 2. 5. 22:08
1. Django REST Framework에서 JWT Token 설정하기
Django에서 API 인증을 위해 JWT(Json Web Token)를 사용하는 방법을 정리합니다.
1.1 필수 패키지 설치
먼저, djangorestframework와 djangorestframework-simplejwt를 설치합니다.
pip install djangorestframework djangorestframework-simplejwt
1.2 Django 설정 변경
settings.py 파일에서 REST Framework 및 SimpleJWT를 설정합니다.
INSTALLED_APPS = [
'rest_framework',
'rest_framework_simplejwt',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
1.3 URL 설정
Django의 urls.py에서 JWT 관련 엔드포인트를 등록합니다.
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'),
]
1.4 사용자 인증 View 작성 (선택 사항)
기본 제공되는 TokenObtainPairView를 그대로 사용하거나, 사용자 정보를 포함하는 커스텀 뷰를 만들 수도 있습니다.
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['username'] = user.username
return token
class CustomTokenObtainPairView(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer
이제 JWT 토큰을 생성하고 사용할 준비가 완료되었습니다.
2. JWT Token을 사용하여 API 호출하기
JWT를 사용하여 API를 호출하는 방법을 정리합니다.
2.1 로그인하여 JWT 토큰 받기
먼저, api/token/ 엔드포인트를 사용하여 JWT 토큰을 발급받습니다.
curl -X POST "http://localhost:8000/api/token/" \
-H "Content-Type: application/json" \
-d '{"username": "testuser", "password": "password123"}'
응답 예시:
{
"refresh": "your_refresh_token_here",
"access": "your_access_token_here"
}
✅ (Windows사용자일경우) PowerShell에서 JWT 토큰을 파일로 저장
PowerShell에서 Invoke-RestMethod로 토큰을 받아 JSON 형식으로 파일에 저장할 수 있습니다.
🚀 PowerShell 스크립트
# API 호출하여 JWT 토큰 가져오기
$response = Invoke-RestMethod -Uri "http://localhost:8000/api/token/" `
-Method Post `
-Headers @{"Content-Type"="application/json"} `
-Body '{"username": "api_user", "password": "1"}'
# 토큰을 JSON 파일로 저장
$response | ConvertTo-Json | Out-File "token.json"
# 저장된 파일 확인
Write-Output "토큰이 token.json 파일에 저장되었습니다."
✅ 설명
- Invoke-RestMethod로 JWT 토큰을 요청
- 받은 응답(JSON 데이터)를 ConvertTo-Json으로 변환
- Out-File을 사용해 token.json 파일에 저장
2.2 발급된 JWT Token을 사용하여 API 호출하기
이제 발급받은 access 토큰을 사용하여 인증이 필요한 API를 호출할 수 있습니다.
curl -X GET "http://localhost:8000/protected-api/" \
-H "Authorization: Bearer your_access_token_here"
예제 코드 (Python requests 사용)
import requests
access_token = "your_access_token_here"
headers = {
"Authorization": f"Bearer {access_token}"
}
response = requests.get("http://localhost:8000/protected-api/", headers=headers)
print(response.json())
2.3 토큰 갱신하기
access 토큰이 만료되었을 때 refresh 토큰을 사용하여 새로운 access 토큰을 발급받을 수 있습니다.
curl -X POST "http://localhost:8000/api/token/refresh/" \
-H "Content-Type: application/json" \
-d '{"refresh": "your_refresh_token_here"}'
응답 예시:
{
"access": "new_access_token_here"
}
3. 결론
Django REST Framework에서 JWT를 설정하고 사용하는 방법을 살펴보았습니다. JWT를 이용하면 API 요청 시 안전한 인증을 유지하면서도, 세션을 관리하지 않고도 효율적인 인증 시스템을 구축할 수 있습니다.
이제 Django REST API에서 JWT 기반 인증을 활용하여 보안을 강화해 보세요! 🚀
'Python > Django Framework (DRF)' 카테고리의 다른 글
| Django Settings 관리하기: 로컬과 프로덕션 환경 분리 전략 (0) | 2025.02.12 |
|---|---|
| Django REST Framework에서 Basic Token 인증 방식 사용하기 (1) | 2025.02.06 |
| [CentOS] MySql 설치 오류 (2) | 2025.01.09 |
| Windows IIS 서버에 Django 애플리케이션 배포 (2) | 2024.12.09 |
| Django CheatSheet2. Django에서 API를 호출하는 예제 (1) | 2024.11.27 |
- Total
- Today
- Yesterday
- 로또 1164회 당첨
- 토치비전
- chat gpt 모델 api 가격 예측
- 1165회 로또
- 재테크
- chat gpt 한국어 가격
- 장고 orm sql문 비교
- 자동매매
- 로또 ai
- chat gpt 가격 예상
- chat gpt 4o 예산
- 주식투자
- 클래스형 뷰
- chat gpt api 비용 계산
- 케라스
- 주린이탈출
- 차트분석
- 티스토리챌린지
- Python
- 1164회 로또
- chat gpt 모델 별 가격
- 인공지능 로또 예측
- 기술적분석
- 오블완
- chat gpt 모델별 예산
- Numpy
- 골든크로스
- 퀀트투자
- 자동매매로직
- 주식공부
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |