Spring 安全:拒绝特定角色访问资源

Spring security: deny access to resource to specific role

我正在使用 Spring 编写一组其余 Web 服务,但无法为某些逻辑配置 Spring 安全性。 我有这些类型的资源:

我对最后一个要求有疑问。我尝试了以下方法:

        http
        .authorizeRequests()  
            .antMatchers("/resource1").permitAll()                
            .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource4").not().hasAuthority("ROLE_USER")
            .anyRequest().fullyAuthenticated()
            .and().requestCache().requestCache(new NullRequestCache())
            .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
            .and().csrf().disable();

这段代码和我需要的最相似:

但是,问题出在 "resource4"...如果用户通过身份验证,一切正常(只有没有任何角色 USER 的用户才能访问资源)...问题是 Spring 允许访问 未经身份验证的用户 (因为我认为它认为他们不属于规则 USER,这是正确的)

知道如何将资源配置为某些角色无法访问,但必须经过身份验证吗?

您可以使用 .access(String expression) 它允许指定 URL 受任意表达式保护

with expression = "not( hasRole('USER') ) and isAuthenticated()"

导致

http
    .authorizeRequests()  
        .antMatchers("/resource1").permitAll()                
        .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
        .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
        .antMatchers(HttpMethod.GET,"/resource4").access("not( hasRole('USER') ) and isAuthenticated()")