네, JWT 토큰을 이용해 로그인 세션 만료를 구현할 수 있습니다. JWT 기반 인증에서 세션 만료를 처리하는 일반적인 방법은 액세스 토큰과 리프레시 토큰을 사용하는 것입니다. 아래는 JWT를 이용한 로그인 세션 만료를 구현하는 방법에 대한 예제입니다.
먼저, djangorestframework
와 djangorestframework-simplejwt
패키지를 설치합니다.
pip install djangorestframework djangorestframework-simplejwt
# settings.py
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework_simplejwt.token_blacklist',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
# JWT 설정
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
}
# views.py
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'),
]
import axios from 'axios';
import Cookies from 'js-cookie';
const api = axios.create({
baseURL: '<http://your-api-domain.com>',
withCredentials: true,
});
function login(username, password) {
api.post('/api/token/', { username, password })
.then(response => {
const { access, refresh } = response.data;
Cookies.set('access_token', access, { expires: 5 / 1440 }); // 5분 동안 유효
Cookies.set('refresh_token', refresh, { expires: 1 }); // 1일 동안 유효
startTokenRefreshInterval();
})
.catch(error => {
console.error('로그인 실패:', error);
});
}
function startTokenRefreshInterval() {
setInterval(() => {
const refreshToken = Cookies.get('refresh_token');
if (refreshToken) {
api.post('/api/token/refresh/', { refresh: refreshToken })
.then(response => {
const { access } = response.data;
Cookies.set('access_token', access, { expires: 5 / 1440 }); // 5분 동안 유효
})
.catch(error => {
console.error('토큰 갱신 실패:', error);
logout();
});
}
}, 4 * 60 * 1000); // 4분마다 토큰 갱신 시도
}
function logout() {
Cookies.remove('access_token');
Cookies.remove('refresh_token');
window.location.href = '/login'; // 로그인 페이지로 리디렉션
}
function getAuthHeaders() {
const accessToken = Cookies.get('access_token');
return accessToken ? { Authorization: `Bearer ${accessToken}` } : {};
}
// 예제 API 요청
function fetchData() {
api.get('/api/data/', { headers: getAuthHeaders() })
.then(response => {
console.log('데이터:', response.data);
})
.catch(error => {
console.error('데이터 가져오기 실패:', error);
});
}
// 모든 사용자 활동 이벤트에 대해 타이머를 리셋
window.onload = startTokenRefreshInterval;
document.onmousemove = startTokenRefreshInterval;
document.onkeypress = startTokenRefreshInterval;
위의 예제에서는 액세스 토큰을 5분 동안 유효하게 설정하고, 리프레시 토큰을 1일 동안 유효하게 설정했습니다. 클라이언트 측에서는 액세스 토큰이 만료되기 전에 주기적으로 리프레시 토큰을 사용해 새로운 액세스 토큰을 발급받습니다.
이 방법을 통해 JWT 기반으로 로그인 세션 만료를 효과적으로 관리할 수 있습니다.