简体   繁体   English

在 Spring Boot 中实现“注销”功能

[英]Implement 'logout' functionality in Spring Boot

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.name=访客
security.user.password=tiger 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.我注意到登录没有在我的浏览器中添加任何 cookie。 I am assuming Spring Security creates an HttpSession object for the user.我假设 Spring Security 为用户创建了一个 HttpSession 对象。 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?在基于 Spring Boot 的应用程序中实现“注销”功能的最佳方法是什么?

Late is better than never.迟到总比不到好。 Spring Boot defaults lots of security components for you, including the CSRF protection. Spring Boot 为您默认了许多安全组件,包括 CSRF 保护。 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其中一件事是强制 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.最后一行是重要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM