![HttpSessionListener를 이용한 중복 로그인 방지](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FkM6hg%2FbtsG4WInAtM%2FJDGBhIxeSFXg1oSxuxTYAk%2Fimg.png)
HttpSessionListener를 이용한 중복 로그인 방지Java/spring2024. 4. 30. 14:41
Table of Contents
728x90
프로젝트를 간단하게 진행하다 보니 중복 로그인에 관한 내용을 신경 쓰지 않고 있었다.
Spring Security를 이용하면 수월하다고 하던데
프로젝트에 Spring Security를 적용하지 않아서 급한대로
HttpSessionListener를 이용하여 중복 로그인을 방지해 보았다.
✅ SessionConfig
@Slf4j
@WebListener
public class SessionConfig implements HttpSessionListener {
private static final Map<String, HttpSession> sessions = new ConcurrentHashMap<>();
//중복로그인 지우기
public static boolean loginSessionidCheck(HttpSession session, String userId){
HttpSession currentSession = sessions.putIfAbsent(userId, session);
if (currentSession != null) {
// 이미 로그인된 세션이 있다면 그 세션을 무효화
if (!currentSession.getId().equals(session.getId())) {
currentSession.invalidate();
sessions.put(userId, session); // 새 세션을 저장
return true;
} else {
// 동일 세션 로그인 시도 (정상 로그인)
return false;
}
}
return true;
}
@Override
public void sessionCreated(HttpSessionEvent se) {
log.info("Session Event: {}", se);
sessions.put(se.getSession().getId(), se.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
if(sessions.get(se.getSession().getId()) != null){
sessions.get(se.getSession().getId()).invalidate();
sessions.remove(se.getSession().getId());
}
}
}
이렇게만 해두어도 정상적으로 작동하기는 하는데 기존에 로그인되어있던 PC에서는 아무런 알림도 없이
session이 없어져버려서 알림을 넣는 방법도 생각해 봐야겠다.
'Java > spring' 카테고리의 다른 글
Bean Validation (1) | 2024.02.26 |
---|---|
Thymeleaf 스프링 통합과 폼 (0) | 2024.02.15 |
Ajax를 통해 파일과 Json 업로드 후 Controller로 받기 (0) | 2023.05.12 |
Spring boot Interceptor Ajax 체크 (Redirect 이슈) (0) | 2023.04.05 |
Spring boot RestAPI 파일 다운로드 (0) | 2023.02.10 |
@요술공주밍키 :: 삽질의흔적
조금씩이라도 꾸준히..