在 Spring Boot 中实现“注销"功能 [英] Implement 'logout' functionality in Spring Boot

查看:106
本文介绍了在 Spring Boot 中实现“注销"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了让基本的安全功能发挥作用,我在 pom.xml 中添加了以下启动包

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>

并在 application.properties 中添加以下两个属性:

And added following two properties to application.properties:

security.user.name=访客
security.user.password=tiger

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

现在,当我点击主页时,我会看到登录框并且登录按预期进行.

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

现在我想实现注销"功能.当用户点击链接时,他/她会被注销.我注意到登录没有在我的浏览器中添加任何 cookie.我假设 Spring Security 为用户创建了一个 HttpSession 对象.真的吗?我是否需要无效"这个会话并将用户重定向到其他页面?在基于 Spring Boot 的应用程序中实现注销"功能的最佳方法是什么?

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?

推荐答案

迟到总比不到好.Spring Boot 为您默认了许多安全组件,包括 CSRF 保护.其中一件事是强制 POST 注销,请参见此处:http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#csrf-logout

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");

最后一行很重要.

这篇关于在 Spring Boot 中实现“注销"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆