네, JWT 토큰을 이용해 로그인 세션 만료를 구현할 수 있습니다. JWT 기반 인증에서 세션 만료를 처리하는 일반적인 방법은 액세스 토큰과 리프레시 토큰을 사용하는 것입니다. 아래는 JWT를 이용한 로그인 세션 만료를 구현하는 방법에 대한 예제입니다.

1. JWT 기반 로그인

서버 측 (Django)

먼저, djangorestframeworkdjangorestframework-simplejwt 패키지를 설치합니다.

pip install djangorestframework djangorestframework-simplejwt

settings.py

# 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

# 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'),
]

2. 클라이언트 측 (JavaScript)

로그인 및 토큰 관리

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;

3. 토큰 만료 및 갱신

위의 예제에서는 액세스 토큰을 5분 동안 유효하게 설정하고, 리프레시 토큰을 1일 동안 유효하게 설정했습니다. 클라이언트 측에서는 액세스 토큰이 만료되기 전에 주기적으로 리프레시 토큰을 사용해 새로운 액세스 토큰을 발급받습니다.

요약

이 방법을 통해 JWT 기반으로 로그인 세션 만료를 효과적으로 관리할 수 있습니다.