Skip to content

Instantly share code, notes, and snippets.

@jecyhw
Last active February 10, 2022 05:59
Show Gist options
  • Save jecyhw/f9f65185dd5d4b284ce4e755637475c7 to your computer and use it in GitHub Desktop.
Save jecyhw/f9f65185dd5d4b284ce4e755637475c7 to your computer and use it in GitHub Desktop.
spring boot ajax session timeout
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';
}
});
**/
@subinsoman
Copy link

worked for me thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment