2017-01-22 107 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");