Popular Posts

Sunday, September 27, 2015

Default Logout with Spring Security

The other day I was trying to implement "logout" functionality for one of my POC using spring security. I couldn't find a better and simple solution for "logout" in spring security as they have it for "login". As we know spring security by default have "formLogin()" built in which will display the login form to the user but it doesn't have anything for logout. So here what I comes up with:

1:  @Configuration  
2:  public class SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {  
3:       @Override  
4:       protected void configure(HttpSecurity http) throws Exception {  
5:            http  
6:                      .csrf()  
7:                      .disable()  
8:                      .and()  
9:                      .authorizeRequests()  
10:                    .anyRequest()  
11:                    .authenticated()  
12:                    .and()  
13:                    .formLogin()  
14:                    .permitAll()  
15:                    .and()  
16:                    .logout()  
17:                    .deleteCookies("remove")  
18:                    .invalidateHttpSession(false)  
19:                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))  
20:                    .logoutSuccessUrl("/login");  
21:       }  

How this works:

Just type "logout" in header address bar and it will delete any user session cookies that spring security creates it by default, invalidates the user session and takes the user back to the default login page. Actually in the backend spring will look for any logout requests made and map it to the default login page after logging out the user. Isn't this simple and cool?

Please comment if you need any help implementing this functionality.