【问题标题】:@PreAuthorize isAnonymous doesn't work on Spring Boot@PreAuthorize isAnonymous 在 Spring Boot 上不起作用
【发布时间】:2019-08-02 17:15:14
【问题描述】:

@PreAuthorizeisAnonymous() 似乎不适用于 Spring(实际上是 Spring Boot)。

这是我的代码:

@RestController
@RequiredArgsConstructor
public class ValidateCodeController {

    private final @NonNull ValidateCodeProcessorHolder validateCodeProcessorHolder;

//  @PreAuthorize("permitAll()")
    @PreAuthorize("isAnonymous()")
    @GetMapping(SecurityConstants.VALIDATE_CODE_URL_PREFIX + "/{type}")
    public void creatCode(HttpServletRequest request, HttpServletResponse response,
                          @PathVariable String type) throws Exception {
        validateCodeProcessorHolder.findValidateCodeProcessor(type)
                .create(new ServletWebRequest(request, response));
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/test")
    public HttpEntity<?> resource() {
        return ResponseEntity.ok(123);
    }

}

但我收到了 HTTP 403 Forbidden 响应:

{
    "timestamp": "2019-08-02T08:36:50.859+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/code/email"
}

/test

{
    "timestamp": "2019-08-02T08:36:48.202+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/test"
}

在我的配置文件中。

@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
//              If use this, it can work.
//                .antMatchers("/code/*").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

我希望得到资源。

【问题讨论】:

    标签: spring spring-boot spring-security spring-security-oauth2


    【解决方案1】:

    我们不能将isAnonymous()permitAll()@PreAuthorize 一起使用。这些可以用在configure(HttpSecurity http)

    正确的方法是使用ROLE_NAME

    @PreAuthorize("hasRole('ADMIN')")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    

    我们也可以在 configure(HttpSecurity http) 中实现这一点,如下所示

         http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/login","/logout").permitAll() 
         .antMatchers("/admin/**").hasRole("ADMIN") 
         .antMatchers(HttpMethod.GET,"/user/**").hasAnyRole("ADMIN","USER")
         .antMatchers(HttpMethod.POST,"/user/**").hasAnyRole("ADMIN","USER")
         .anyRequest().authenticated();
    

    【讨论】:

      【解决方案2】:

      使用

      @PreAuthorize("hasRole('ADMIN')")
      

      @PreAuthorize("hasAuthority('ROLE_ADMIN')")
      

      参考https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-faq-role-prefix

      【讨论】:

        【解决方案3】:

        在您的 WebSecurityConfig 类中,您具有以下定义:

        ...
        .anyRequest()
        .authenticated()
        ...
        

        您对 Spring que 说所有请求都必须经过身份验证。然后,您的注解@PreAuthorize("isAnonymous()") 将始终为 false 并返回 403 http 代码。

        访问以下链接以查看更多信息:https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html

        【讨论】:

          猜你喜欢
          • 2015-01-30
          • 2018-01-01
          • 2019-01-29
          • 1970-01-01
          • 2017-01-10
          • 2020-06-24
          • 2015-12-09
          • 2015-06-20
          • 2017-11-16
          相关资源
          最近更新 更多