Last active
February 10, 2022 05:59
-
-
Save jecyhw/f9f65185dd5d4b284ce4e755637475c7 to your computer and use it in GitHub Desktop.
spring boot ajax session timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { | |
public AjaxAwareAuthenticationEntryPoint(String loginFormUrl) { | |
super(loginFormUrl); | |
} | |
@Override | |
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { | |
String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With"); | |
if ("XMLHttpRequest".equals(ajaxHeader)) { | |
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Ajax Request Denied (Session Expired)"); | |
} else { | |
super.commence(request, response, authException); | |
} | |
} | |
} | |
/** | |
@Configuration | |
public class SecurityConfig extends WebSecurityConfigurerAdapter { | |
@Autowired | |
private UserDetailsService userDetailsService; | |
@Bean | |
public BCryptPasswordEncoder bCryptPasswordEncoder() { | |
return new BCryptPasswordEncoder(); | |
} | |
@Override | |
protected void configure(AuthenticationManagerBuilder auth) throws Exception { | |
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); | |
} | |
@Override | |
protected void configure(HttpSecurity http) throws Exception { | |
http | |
.headers() | |
.frameOptions().sameOrigin() | |
.and() | |
.authorizeRequests() | |
.antMatchers("/**/create", "/**/recognition", "/**/delete*", "/**/uploadFile*").authenticated() | |
.antMatchers("/**").permitAll() | |
.and() | |
.formLogin() | |
.loginPage("/login?auth") | |
.loginProcessingUrl("/login") | |
.failureUrl("/login?error") | |
.defaultSuccessUrl("/") | |
.usernameParameter("userName") | |
.passwordParameter("password") | |
.permitAll() | |
.and() | |
.logout().logoutSuccessUrl("/login").logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll() | |
.and().csrf() | |
.and().exceptionHandling().authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint("/login")); | |
} | |
} | |
**/ | |
/** | |
$(document).ajaxError(function (e, xhr, options) { | |
if (xhr.status == 403) { | |
window.location.href = 'login'; | |
} | |
}); | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
worked for me thanks