programming study/웹개발

JWT

gu9gu 2023. 1. 13. 02:08

 

1.JWT란

JWT-사전지식-RSA-암호화 (tistory.com)

JSON 웹 토큰 소개 - jwt.io

[JWT] JWT란 무엇인가? (JSON Web Token) 쉽게 정리한 core개념들 (tistory.com)

JWT란? JWT , Session, Cookie 비교 (velog.io)

 

2.  엑세스 토큰 만료 후 리프레쉬 토큰 발급 api 요청은 클라이언트 단에서 해주고 있는데 서버단에서 바로 처리 하면 안 되는지?

 - 서버단에서 바로 처리하지 않고 리프레시 토큰 발급 API를 따로 만든 이유는 아래와 같습니다!

[Spring/Security/JWT] JWT를 사용한 로그인 및 Refresh Token을 활용한 로그인 상태 유지 — 훙성의 기술 블로그 (tistory.com)

1. 서버단에서 클라이언트가 보낸 액세스토큰 만료 시 즉시 리프레시 토큰 검증 후 재발급을 위해서는 클라이언트 단에서 매번 API 요청에 대해 액세스 토큰 뿐 아니라 리프레시 토큰을 같이 보내주어야 하는 부담이 있습니다.

2. 클라이언트 단에서 액세스 토큰으로 API 요청 시 해당 액세스 토큰이 언제 만료되는지에 대해서는 명확하게 알 수 없기 때문에 클라이언트 단에서 액세스 토큰을 통해 API 요청 시 401(Unauthorized) 응답이 온다면 액세스 토큰이 만료된 것으로 간주하고 이 때 리프레시 토큰 발급 요청 api를 호출하여 액세스토큰을 재발급 받는 방식을 주로 이용합니다!

 

- 클라이언트단 코드 예시

// Access Token 가져오기
const accessToken = localStorage.getItem('accessToken');
// Refresh Token 가져오기
const refreshToken = localStorage.getItem('refreshToken');

// API 요청 보내기
fetch('/api/data', {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
    },
})
.then(response => {
    if (response.status === 401) {
        // Access Token이 만료된 경우, 새로운 Access Token을 요청
        return fetch('/api/token/refresh', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'refresh_token': refreshToken
            })
        })
            .then(response => response.json())
            .then(data => {
                // 새로운 Access Token 저장
                localStorage.setItem('accessToken', data.access_token);
                // 새로운 Access Token으로 API 요청 다시 보내기
                return fetch('/api/data', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${data.access_token}`,
                        'Content-Type': 'application/json'
                    },
                });
            });
    } else {
        // Access Token이 유효한 경우, 그대로 API 요청 보내기
        return response;
    }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

'programming study > 웹개발' 카테고리의 다른 글

캐시  (0) 2023.05.02