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

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

问题描述

为了使基本安全功能正常工作,我将以下启动包添加到我的pom.xml

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>

并将以下两个属性添加到application.properties:

And added following two properties to application.properties:

security.user.name = guest

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对象。真的吗?我是否需要使此会话无效并将用户重定向到其他页面?在基于Sprint Boot的应用程序中实现注销功能的最佳方法是什么?

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?

推荐答案

迟到总比没有好。 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");

最后一行是重要的一行。

The last line is the important one.

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

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