弹簧安全性ROLE_ANONYMOUS在启用拒绝默认情况下不起作用

弹簧安全性ROLE_ANONYMOUS在启用拒绝默认情况下不起作用

问题描述:

我已启用拒绝默认安全功能。有了这个,我想在某些控制器上提供匿名访问。为此,我启用了匿名身份验证。弹簧安全性ROLE_ANONYMOUS在启用拒绝默认情况下不起作用

如果我使用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" 
} 

春季安全配置:

@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(),您已经配置您的安全链认证的所有要求 ,这抓住了匿名请求并在它到达控制器之前拒绝它。

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

+1

如果我们需要添加antMatchers(“/”)。permitAll()然后最新使用ROLE_ANONYMOUS? –

+2

@Deepak Agrawal:这是两个不同的事情,网络安全和方法安全。如果两者都使用,则必须知道首先检查网络安全。只有在网络安全通过时才会检查方法安全性。 – dur