当默认拒绝默认时,Spring Security ROLE_ANONYMOUS不起作用

我启用了默认的deny-by-defaultfunction。 有了这个,我想在一些控制器上提供匿名访问。 为此,我启用了匿名身份validation。

如果我使用antmacher.permitAll()工作正常。 但如果我使用@PreAuthorize(value="hasRole('ROLE_ANONYMOUS')") ,控制器对我来说不起作用。

 { "timeStamp": 1488692168652, "success": false, "message": "Full authentication is required to access this resource", "class": "org.springframework.security.authentication.InsufficientAuthenticationException" } 

Spring安全配置:

 @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable(); httpSecurity.httpBasic().disable(); // enable anonymous access httpSecurity.anonymous(); httpSecurity.authorizeRequests() //.antMatchers("/").permitAll() .anyRequest().authenticated(); httpSecurity.addFilterAt(jsonAuthenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); // Call our errorHandler if authentication/authorization fails httpSecurity.exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint()); httpSecurity.exceptionHandling().accessDeniedHandler(new JwtAccessDeniedHandler()); // don't create session httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Custom JWT based security filter httpSecurity.addFilterAfter(jwtAuthenticationTokenFilterBean(), RememberMeAuthenticationFilter.class); // disable page caching httpSecurity.headers().cacheControl().disable(); } 

控制器:

 @RestController @PreAuthorize(value="hasRole('ROLE_ANONYMOUS')") public class HomeController { @RequestMapping("/") String execute() { return "hello"; } } 

当使用@PreAuthorize(value="hasRole('ROLE_ANONYMOUS')")anyRequest().authenticated() ,您已经配置了安全链来validation所有请求,这会捕获匿名请求并拒绝它,然后才能访问控制器。

您可以使用antMatchers("/").permitAll()antMatchers("/").anonymous()来配置以通过安全filter链。