2017-01-22 132 views
1

我有一個使用Spring Boot和Spring Security構建的REST API。我從文檔中看到Spring Security默認在請求/logout時默認登錄當前用戶。但是,我似乎無法得到這個工作。Spring Boot + Spring Security - 無法註銷

這是我的安全配置:

@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" 
} 
+0

你不提供'.logout()' ;見例如https://spring.io/guides/gs/securing-web/。你有什麼要求? – jonrsharpe

+0

我其實嘗試添加.logout();從我見過的幾個不同的例子,但沒有效果。您如何建議更改上述示例以啓用註銷?我正在做的請求是一個「/註銷」的GET請求。 – simbro

+1

是的,配置肯定是被稱爲。我添加了「.logout.permitAll()」我嘗試使用POST方法來「/註銷」,仍然是相同的消息,並沒有註銷。別人使用什麼作爲配置方法? – simbro

回答

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