Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement 'logout' functionality in Spring Boot

To get a basic security feature working, I added the following starter package to my pom.xml

    <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-security</artifactId>     </dependency> 

And added following two properties to application.properties:

security.user.name=guest
security.user.password=tiger

Now when I hit my homepage, I get the login box and login works as expected.

Now I want to implement the ‘logout’ feature. When the user clicks on a link, he/she gets logged out. I noticed that the login doesn’t add any cookie in my browser. I am assuming Spring Security creates an HttpSession object for the user. Is that true? Do I need to ‘invalidate’ this session and redirect the user to some other page? What’s the best way to implement the ‘logout’ feature in a Spring Boot based application?

like image 405
DilTeam Avatar asked May 14 '14 17:05

DilTeam


People also ask

How would you implement the logout functionality in spring boot application?

Basic Configuration The basic configuration of Spring Logout functionality using the logout() method is simple enough: @Configuration @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { http //... .

What does spring logout do?

Logout Configuration logout . Spring security provides flexibility to change the URL. If CSRF protection is active (default), Spring security expects the logout request must of POST type, we can use the GET logout request by disabling the CSRF protection.

What is the default logout URL defined by spring security?

According to Spring Security 4.0.0 document: 4.2.4 Logout Handling. The logout element adds support for logging out by navigating to a particular URL. The default logout URL is /logout, but you can set it to something else using the logout-url attribute.


1 Answers

Late is better than never. Spring Boot defaults lots of security components for you, including the CSRF protection. One of the things that does is force POST logout, see here: http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#csrf-logout

As this suggests you can override this, using something along the lines of:

http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN")                                       .anyRequest().fullyAuthenticated() .and() .formLogin().loginPage("/login").failureUrl("/login?error").permitAll() .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login"); 

The last line is the important one.

like image 82
mmeany Avatar answered Sep 21 '22 18:09

mmeany