@PreAuthorize isAnonymous在Spring Boot上不起作用

时间:2019-08-02 08:41:49

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

@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禁止响应:

{
    "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();
    }

}

我希望得到资源。

3 个答案:

答案 0 :(得分:2)

我们不能将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();

答案 1 :(得分:0)

使用

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

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

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

答案 2 :(得分:0)

在您的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