Spring Security ROLE_ANONYMOUS does not work when deny-by-default is activated

可紊 提交于 2019-12-31 07:55:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!