问题
To get a basic security feature working, I added 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. Basically, when user clicks on a link, 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 user to some other page? What’s the best way to implement ‘logout’ feature in a Sprint Boot based application?
回答1:
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.
来源:https://stackoverflow.com/questions/23661492/implement-logout-functionality-in-spring-boot