IT 웹개발/스프링(Spring)

Spring HttpSessionListener를 이용해 로그인 세션 관리하여 중복 로그인 방지 방법

펌킨고구마 2024. 3. 27. 20:52
728x90
반응형

보안관련해서 다중 로그인을 막아야 한다고 한다.

다른 기기에서 접속하였을 경우, 로그인된 현재 기기를 자동으로 로그아웃 시키고 alert 알림창을 띄우기....

 

확인해본 결과, 기존 소스에는 DB를 이용하여 로그인했을때 DB에 데이터를 넣어 관리했었다.

다른사람이 접속하면 데이터베이스내의 데이터와 비교하여 확인하는 식..? 

 

근데 그러면 괜히 쿼리도 많이 보내고 하여 세션으로 중복 로그인 방지 방법을 찾아봤다.

 

 

Spring Security를 이용하여 처리 하는 방법이 있고,

Spring HttpSessionListener를 이용하여 처리 하는 방법이 있었다.

 

이중에 나는 Spring HttpSessionListener를 이용하여 처리하는 방법을 작성할 예정

 

애초에 나는 누구한테 설명해줄 정도는 아니라 그냥 내가 여기저기 보고 작성한 소스를 업로드한 것이다. 나중에 또 쓸때가 있겠지

 

public class SessionConfig implements HttpSessionListener {
    
    private static Map<String, HttpSession> sessions = new ConcurrentHashMap<String, HttpSession>(32);
    
    
	//중복로그인 지우기 추가 
	public synchronized static String getSessionidCheck(String type, String compareId){
		String result = "";
		for( String key : sessions .keySet() ){
			HttpSession hs = sessions .get(key);
			if(hs != null &&  hs.getAttribute(type) != null && hs.getAttribute(type).toString().equals(compareId) ){
				result =  key.toString();
			}
		}
		removeSessionForDoubleLogin(result);
		return result;
	}
	
	private static void removeSessionForDoubleLogin(String userId){    	
		System.out.println("remove userId : " + userId);
		if(userId != null && userId.length() > 0){
			sessions .get(userId).invalidate();
			sessions .remove(userId);    		
		}
	}
	
	
    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
        synchronized(sessions ){
            String sessionId = arg0.getSession().getId();
            sessions .put(sessionId, arg0.getSession());
        }
        
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        synchronized(sessions ){
            String sessionId = arg0.getSession().getId();
            sessions .remove(sessionId);
        }
    }

 

728x90
반응형
LIST