问题
I had enabled deny-by-default feature of security. With this I want to provide anonymous access on some controllers. For that I had enabled Anonymous authentication.
If I use antmacher.permitAll() works fine.
But if I am using @PreAuthorize(value="hasRole('ROLE_ANONYMOUS')") with controllers does not work for me.
{
"timeStamp": 1488692168652,
"success": false,
"message": "Full authentication is required to access this resource",
"class": "org.springframework.security.authentication.InsufficientAuthenticationException"
}
Spring security Configuration:
@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();
}
Controller:
@RestController
@PreAuthorize(value="hasRole('ROLE_ANONYMOUS')")
public class HomeController {
@RequestMapping("/")
String execute() {
return "hello";
}
}
回答1:
When using @PreAuthorize(value="hasRole('ROLE_ANONYMOUS')") and anyRequest().authenticated(),
you have configured your security chain to authenticate all requests, this catches the anonymous request and rejects it, before it gets to the controller.
Either you can configure using antMatchers("/").permitAll() or antMatchers("/").anonymous() to pass through the security filter chain.
来源:https://stackoverflow.com/questions/42605008/spring-security-role-anonymous-does-not-work-when-deny-by-default-is-activated