Session을 이용한 로그인 처리~~~!! 

내부에서만 사용하거나 단순한 사이트로 굳이 Security 까지 추가할 필요가 없는 경우 사용하면 좋겠다. 

 

프로세스는 ~~~ 

모든 요청을 감시하는 Interceptor 생성! 

로그인에 성공하면 Session값을 설정하고 

요청이 올때마다 Interceptor가 Session 값이 있는지 확인 후 없다면 로그인페이지로 리턴시키걸로~ 

 

즈아~~ 시작! 

 

1.  Interceptor 생성 
요청이 들어오면 Session 지정해둔 Session 값을 확인하고 없다면 로그인페이지로 리다이렉트 처리한다. 

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		if( request.getSession().getAttribute(Consts.AUTHORIZED) == null  ) {
			response.sendRedirect(request.getContextPath() +"/login");
			return false;
		}
		return true;
	}
}

 

2. Interceptor 등록! 
모든 요청을 검사하도록  .addPathPatterns("/**") 로 설정 후 
Js, css 파일 등이 들어있는 resource 디렉토리 하위는 무시하도록 exclude 처리한다. 
로그인을 위한 요청도 exclude 처리~~!! 

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter  {
	
	 @Override
	    public void addInterceptors(InterceptorRegistry registry) {
	        registry.addInterceptor(new LoginInterceptor())
	                .addPathPatterns("/**")
	                .excludePathPatterns("/resources/**")
	                .excludePathPatterns("/login/**"); 
	    }
	 
}

 

 

3. Login/out 세션작업~~!! 

(위치는 각자 로그인/아웃 파일에 작성!)

// Login 
// 비밀번호, 잠금여부 등등 모든 조건이 맞아 로그인에 성공하게되면 Session 값을 추가해준다. 
request.getSession().setAttribute(Consts.AUTHORIZED, Consts.AUTHORIZED_VALUE);

// Logout
// 로그아웃시 Session 값을 제거해준다. 
request.getSession().removeAttribute(Consts.AUTHORIZED); 

 

4. Session 시간 설정~ 

초단위 결과를 안쓰고 굳이 (60 * 60 * 24)로 쓴 이유는~ 보고 바로 알수있게 하기 위함~~

 시간 같은건 이렇게 해주면 같이 일하는 사람 편하겠죠?  ( 암산이 빠르면 필요없겠지만.. 나는 좋음.. ^^! ) 

public class SessionListener  implements HttpSessionListener{

	@Override
	public void sessionCreated(HttpSessionEvent session) {
		session.getSession().setMaxInactiveInterval(60 * 60 * 24);// 24 시간으로 설정
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
	}

}

 

 

Session 만료되면 자동으로 로그인페이지로 보내볼까??? 

시간 설정할때 보니 아래 있는 sessionDestroyed가 Session이 만료되면 호출된다고한다. 

요고요고 ~ ↓ 


	@Override
	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
		 HttpSession session = httpSessionEvent.getSession();
		
	}


음~~

그럼 여기서 로그인 페이지로 redirect해주면 되겠군! 하고 생각할 수 있다. 

자~! 여기서 생각해봐야할건 

sessionDestroyed 메소드는 사용자의 요청으로 호출되는게 아니라

Session이 만료되었을때 호출 된다는 것이다. 

즉 ~ R e q u e s t 가 없 다 는 뜻 ! !  

요청(request)이 없으니 redirect 할곳도 없습니다~ ~!

혹시~~~~ redirect 처리한다고 시간낭비하지 않기로 ..  ^^ 

 

보통 Session 만료 검사를 Interceptor에서 필터링으로 처리하는데 

우린 이미 interceptor 처리하고있으니~ 추가안해도 될듯

 

그래도~~~!! 

Session 만료되기 전 뭔가 알림을  설정하고자 한다면 

스크립트단에서 

setInterval 같은 함수를 이용해 10분 간격으로 체크!~

이벤트가 생기면 체크값을 초기화~ 이벤드가 없어서 5번째까지 온다면 

"세션이 10분 남았음"  표기를 해주는것도 방법일 듯 하다. ~ 

+ Recent posts