【问题标题】:Spring Security ROLE_ANONYMOUS does not work when deny-by-default is activated激活默认拒绝时,Spring Security ROLE_ANONYMOUS 不起作用
【发布时间】:2017-03-05 05:51:16
【问题描述】:

我启用了默认拒绝安全功能。有了这个,我想在一些控制器上提供匿名访问。为此,我启用了匿名身份验证。

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

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    使用@PreAuthorize(value="hasRole('ROLE_ANONYMOUS')")anyRequest().authenticated() 时, 您已将安全链配置为对所有请求进行身份验证,这会在匿名请求到达控制器之前捕获并拒绝它。

    您可以使用antMatchers("/").permitAll()antMatchers("/").anonymous() 进行配置以通过安全过滤器链。

    【讨论】:

    • 如果我们需要添加antMatchers("/").permitAll() 那么ROLE_ANONYMOUS有什么用呢?
    • @Deepak Agrawal:这是两个不同的东西,网络安全和方法安全。如果您同时使用两者,您必须知道首先检查网络安全。仅在通过 Web 安全性时才检查方法安全性。
    猜你喜欢
    • 2018-01-15
    • 2017-01-06
    • 2015-09-15
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多