spring boot Ajax session timeout 설정 - fehead/sample_spring_mvc GitHub Wiki

Ajax session timeout 설정

AjaxAwareAuthenticationEntryPoint 클래스 작성

	// Spring security + Ajax session timeout issue
	public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
		public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
			super(loginUrl);
		}

		@Override
		public void commence(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException authException) throws IOException, ServletException {
			String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
			boolean isAjax = "XMLHttpRequest".equals(ajaxHeader);
			if (isAjax) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN, "Ajax REquest Denied (Session Expired)");
			} else {
				super.commence(request, response, authException);
			}
		}
	}

Spring Security 설정에 등록

	@Configuration
	@EnableWebSecurity
	public class ConfigSecurity extends WebSecurityConfigurerAdapter {
		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.csrf().disable()
			.authorizeRequests()
				.antMatchers("/education/**").hasAnyAuthority("ROLE_USER","ROLE_ADMIN")
							// ....
			.and()
				.exceptionHandling().authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint("/login"));
		}
	}

ajax 설정

  • 공통으로 쓰는 html, jsp파일에 아래 내용을 넣음 (예 sub_layout.jsp)
	$.ajaxSetup({
		cache:false,
		error: function(xhr, status, err) {
			console.log(xhr.status);
			if (xhr.status == 401) {
				alert("인증에 실패 했습니다. 로그인 페이지로 이동합니다.");
				location.href = "/logout";
			 } else if (xhr.status == 403) {
				alert("세션이 만료가 되었습니다. 로그인 페이지로 이동합니다.");
				location.href = "/login";
			 }
		 }
	});
  • Ajax 호출문에서 error: 문 제거
	$.ajax({
		url: 'listCore',
		type: 'POST',
		data: dataForm,
		success: function(result, status,xhr){
			$("#listBox > tbody").html(result);
		},
				/******* 이부분 삭제 혹은 주석처리
		error: function(xhr, status, err) {
			console.log(xhr.status);
			}
				*/
	});