在Spring Boot中实现"注销"功能

Dil*_*eam 26 java spring-security spring-boot

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

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

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

现在当我点击我的主页时,我得到了登录框并且登录按预期工作.

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

mme*_*any 79

迟到总比没有好.Spring Boot默认为您提供许多安全组件,包括CSRF保护.其中一件事就是强制POST注销,请看这里:http://docs.spring.io/spring-security/site/docs/3.2.4.RELEASE/reference/htmlsingle/#csrf-logout

这表明你可以使用以下内容来覆盖:

http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")                                      
.anyRequest().fullyAuthenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
Run Code Online (Sandbox Code Playgroud)

最后一行是重要的一行.

  • 我到处寻找这个,谢谢,有时候我觉得Spring Boot做了太多的魔术并且让这样的东西难以追踪 (4认同)
  • 简单的`.logout.permitAll()`会成功.它将重定向到`login /?logout` (2认同)