【问题标题】:Spring Boot + Spring Security - unable to log outSpring Boot + Spring Security - 无法注销
【发布时间】:2017-01-22 14:42:21
【问题描述】:

我有一个使用 Spring Boot 和 Spring Security 构建的 REST API。我从文档中读到 Spring Security 在请求/logout 时默认将当前用户注销。但是,我似乎无法让它工作。

这是我的安全配置:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
            .httpBasic()
                .and()
            .csrf().disable();
    } 
}

但是,当我向/logout 发出请求时,我收到以下错误:

{
    "timestamp": 1485096094269,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/login"
}

【问题讨论】:

  • 你不提供.logout();参见例如spring.io/guides/gs/securing-web。你提出什么要求?
  • 我实际上尝试添加 .logout();从我见过的几个不同的例子中,但没有效果。您如何建议更改上述示例以启用注销?我发出的请求是对“/logout”的 GET 请求。
  • 是的,配置肯定被调用了。我添加了“.logout.permitAll()”,我尝试使用 POST 方法来“/logout”,但仍然是相同的消息并且没有注销。其他人使用什么作为配置方法?
  • 在使用基本身份验证时尝试注销也不起作用,下一个请求仍然发送身份验证标头,用户将再次登录。注销和基本身份验证不能同时使用。
  • 我明白了,我不知道。那么你会推荐使用摘要身份验证吗?或者我是否需要使用带有“/logout”请求映射的自定义方法手动使会话无效?

标签: java spring-boot spring-security


【解决方案1】:

也许回答这个问题有点晚了,但任何人都可以有用。

configure() 方法中缺少logout() 调用,例如:

http.authorizeRequests()
        .anyRequest().fullyAuthenticated()
        .and()
        .httpBasic()
        .and()
    .logout() // This is missing and is important
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login");

您也可以配置自己的登录页面:

http.authorizeRequests()
        // this allows the root and resources to be available without logging in
        .antMatchers("/", "/resources/**").permitAll()
        // any other type of request will need the credentials
        .anyRequest().authenticated()
        .and()
    // uses the custom login form
    .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home") // redirect to home page
        .failureUrl("/login?error") // redirect to error page
        .permitAll()
        .and()
    // logout and redirect to login page
    .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login");

【讨论】:

  • 和我一起为logout工作。谢谢
  • 注销仍然对我不起作用。得到一个 404。完全复制了第一个块。
  • @SledgeHammer 您可能没有/logout/login 资源,因此您得到404,您可以尝试更新该部分。我希望这会有所帮助。
【解决方案2】:

如果使用 AngularJS,请检查是否使用 withHttpOnlyFalse()

.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

https://stackoverflow.com/a/43204307/1767316

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 2011-06-28
    • 2014-04-23
    • 2014-02-02
    • 2012-12-04
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多