PongWorld 프로젝트
인증되지 않은 유저 접근 막기
huipark
2024. 4. 2. 16:40
인증되지 않은 유저가 URL을 통해 직접 페이지로 접근하는 걸 막아보자.
아이디어 :
로그인된 유저는 메모리에 accessToekn 을 가지고 있다. url 로 직접적으로 접근을 할 때 메모리에 accessToken 이 없다면 loginPage 로 리다이렉션 시켜준다. 어디서 할까 고민을 했는데 모든 페이지에서 공통적으로 제일 처음 connetionWebScoket 의 연결 상태를 확인하는데 이때 accessToken 이 사용되므로 이 과정에서 정상적인 유저인지 판단을 할 것이다.
구현 :
기존의 accessToken 을 재발급받는 함수가 있는데 기존의 로직에서 token 재발급에 실패를 하면 loginPage 로 리다이렉션을 시켜준다.
export const refreshAccessToken = async () => {
try {
const res = await fetch(`${API_URL}/tcen-auth/refresh-token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
refresh: sessionStorage.getItem('refresh_token'),
}),
});
const data = await res.json();
console.log(data);
if (res.ok) {
setToken(data.data.access);
} else {
alert('Please try again.');
window.location.href = '/';
}
} catch (error) {
console.log(error);
}
};
UPDATE :
위에 코드를 구현할때는 생각을 못했는데 sesstionStorage 에 user 정보들이 있어서 그 정보들을 지우고 서버에 따로 logout 요청을 해줘야 해서 매번 해당 코드들을 작성하는 건 번거로움으로 따로 함수로 작성해서 재사용하는 방식으로 변경했다.
if(로그아웃 해야함)
logout();
export const logout = async () => {
sessionStorage.clear();
try {
const response = await fetch(`${API_URL}/tcen-auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`,
},
});
if (response.ok) {
console.log('로그아웃 성공');
} else {
console.error('로그아웃 실패');
}
} catch (error) {
console.error('로그아웃 중 오류 발생', error);
}
cws.close();
window.location.href = '/';
};
문제 :
지금 서버에서 https 설정을 하지 않아서 쿠키에 refreshToken 을 저장하지 않고 sesstionStorage 에 저장돼 XSS 공격에 취약해 보안에 좋지 않지만 아직 향후 서버에서 refreshToken 을 쿠키에 관리하는 방식으로 변경을 할 것이다.