Spring Boot + Spring Security - 无法注销

时间:2017-01-22 14:42:22

标签: java spring-boot spring-security

我有一个使用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"
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

如果使用AngularJS,请使用withHttpOnlyFalse()

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

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