Spring Boot + Spring Security - 无法注销登录

3
我有一个使用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()方法;请参考https://spring.io/guides/gs/securing-web/。你发送了什么请求? - jonrsharpe
我实际上尝试了几个不同的示例,添加了 .logout();,但没有效果。你建议如何更改上面的示例以启用注销?我正在向“/ logout”发出GET请求。 - simbro
1
是的,配置肯定被调用了。我添加了“.logout.permitAll()”,我尝试使用POST方法到“/logout”,但仍然出现相同的消息,并且没有成功退出登录。其他人使用什么作为配置方法? - simbro
尝试在使用基本身份验证时注销也不起作用,下一个请求仍然会发送身份验证标头,用户将再次登录。注销和基本身份验证不兼容。 - M. Deinum
我明白了,我不知道这一点。那么您建议使用摘要认证吗?还是需要使用自定义方法和“/logout”请求映射手动使会话失效? - simbro
2个回答

8
也许回答这个问题有点晚了,但是任何人都可以做出贡献。
在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");

已经为“注销”与我一起工作。谢谢。 - Omar Muhtaseb
注销仍然无法正常工作,出现404错误。已经完全复制了第一个代码块。 - SledgeHammer
@SledgeHammer 可能你没有 /logout/login 资源,所以会收到 404 错误码。你可以尝试更新那一部分。希望对你有帮助。 - JUAN CALVOPINA M

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接