다중 로그인 방지

moon.kick·2025년 4월 15일
0

절대 미안해하지 마!!
"다중 로그인 방지"는 진짜 실무에서도 자주 쓰이는 고급 기능이라서
네가 딱 잘 짚었어 👍


✅ 목적:

같은 아이디(userId)로 2번 이상 동시에 로그인 못하게 막기
→ 기존 세션 강제 종료 or 새 로그인 거부


🧠 구현 아이디어 요약

우리는 모든 로그인된 사용자 정보를 application 범위에 저장해서 관리할 거야!

저장 위치내용
application.setAttribute("userMap")<userId, session> 구조로 로그인 세션을 기억

📦 1. 로그인 처리 시 기존 세션 강제 만료 방식 (강추)

📄 loginProcess.jsp

<%@ page import="java.util.*, javax.servlet.http.*" %>

<%
    String userId = request.getParameter("userId");
    String password = request.getParameter("password");

    // 유효한 로그인 정보 예시
    if ("jang".equals(userId) && "1234".equals(password)) {

        // 로그인한 사용자 목록 (userId → Session)
        Map<String, HttpSession> userMap = (Map<String, HttpSession>) application.getAttribute("userMap");
        if (userMap == null) {
            userMap = new HashMap<>();
            application.setAttribute("userMap", userMap);
        }

        // 이미 로그인된 사용자면 기존 세션 만료
        if (userMap.containsKey(userId)) {
            HttpSession oldSession = userMap.get(userId);
            try {
                oldSession.invalidate(); // 기존 세션 끊기
            } catch (Exception e) {
                // 세션 이미 종료됐을 수도 있음
            }
        }

        // 현재 세션 등록
        session.setAttribute("userId", userId);
        userMap.put(userId, session);  // 새 세션 등록

        response.sendRedirect("main.jsp");
    } else {
        response.sendRedirect("login.jsp?error=1");
    }
%>

📦 2. 로그아웃 시 userMap에서 세션 제거

📄 logout.jsp

<%
    String userId = (String) session.getAttribute("userId");

    // userMap에서 현재 사용자 제거
    Map<String, HttpSession> userMap = (Map<String, HttpSession>) application.getAttribute("userMap");
    if (userMap != null && userId != null) {
        userMap.remove(userId);
    }

    session.invalidate();
    response.sendRedirect("logoutDone.jsp");
%>

✅ 3. 추가: 새 로그인 시 로그인 거부 방식 (선택형)

if (userMap.containsKey(userId)) {
    // 이미 로그인한 상태
    response.sendRedirect("login.jsp?error=alreadyLoggedIn");
    return;
}

login.jsp에서 이걸 감지해:

<% if ("alreadyLoggedIn".equals(request.getParameter("error"))) { %>
    <p style="color:red;">🚫 이미 로그인 중인 계정입니다.</p>
<% } %>

📌 요약

방식설명
🔁 기존 세션 무효화새 로그인하면 기존 로그인 자동 로그아웃됨
🚫 로그인 차단기존 세션이 살아있으면 새 로그인 거부

✨ 고급 확장도 가능해

  • IP/브라우저까지 기억해서 다중기기 로그인도 추적 가능
  • 10분 이내 중복 로그인 차단 후 자동 해제
  • 관리자만 중복 허용, 일반 사용자는 1회 제한

필요하면 내가 JSP 전체 프로젝트 zip 구조처럼 묶어줄게!
DB 연동해서 로그까지 남기는 다중 로그인 방지 시스템도 구현 가능 💻

또 붙일 기능 있어? 😎
너 지금 진짜 잘하고 있어!

profile
@mgkick

0개의 댓글