Java 在 Spring Boot 中实现“注销”功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23661492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implement 'logout' functionality in Spring Boot
提问by DilTeam
To get a basic security feature working, I added the following starter package to my pom.xml
为了获得基本的安全功能,我在 pom.xml 中添加了以下启动包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
And added following two properties to application.properties:
并向 application.properties 添加以下两个属性:
security.user.name=guest
security.user.password=tiger
security.user.name=访客
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?
现在我想实现“注销”功能。当用户点击链接时,他/她会被注销。我注意到登录没有在我的浏览器中添加任何 cookie。我假设 Spring Security 为用户创建了一个 HttpSession 对象。真的吗?我是否需要“无效”此会话并将用户重定向到其他页面?在基于 Spring Boot 的应用程序中实现“注销”功能的最佳方法是什么?
采纳答案by mmeany
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
迟到总比不到好。Spring Boot 为您默认了许多安全组件,包括 CSRF 保护。其中一件事是强制 POST 注销,请参见此处: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.
最后一行是重要的。