Spring 启动安全 - Ant Matcher 不工作

Spring Boot Security - Ant Matcher doesn't work

我正在尝试熟悉 spring 引导安全性,我的 API 是一个简单的 GET/POST 到 127.0.0.1:8080/employee/ 使用像这样的简单自动配置。

@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    @Configuration
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("user1").password("{noop}user1").authorities("USER").and()
                    .withUser("user2").password("{noop}user2").authorities("USER").and()
                    .withUser("admin").password("{noop}admin").authorities("ADMIN");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/employee/**").authorizeRequests().anyRequest().hasRole("ADMIN");
        }
    }
}

这总是给我 403 Forbidden。 试过这个:- antMatcher("/employee*"),适用于任何用户。我能得到一些帮助来理解这种模式是如何工作的吗,我只需要将“/employee”或“/employee/”或“/employee/1”限制为管理员。

您当前的配置将仅限制 employee 下的任何路径,例如employee/1 但不是 /employee。此外,当您返回 authorizeRequests 时,您没有对 employee 匹配器执行任何操作,然后配置 anyRequest 具有角色 ADMIN

employee 及其下面的任何路径限制为 ADMIN

     http.authorizeRequests().antMatchers("/employee**", "/employee/**").hasRole("ADMIN").httpBasic();

使用** 将捕获路径中的目录。

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html

https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/util/matcher/AntPathRequestMatcher.html

Using a pattern value of /** or ** is treated as a universal match, which will match any request. Patterns which end with /** (and have no other wildcards) are optimized by using a substring match — a pattern of /aaa/** will match /aaa, /aaa/ and any sub-directories, such as /aaa/bbb/ccc.

我还建议通过 @WebMvcTest 切片测试

测试您的安全配置

https://www.baeldung.com/spring-security-integration-tests

根据上面的一个简单示例,

@RunWith(SpringRunner.class)
@WebMvcTest(SecuredController.class)
public class SecuredControllerWebMvcIntegrationTest {

    @Autowired
    private MockMvc mvc;

    // ... other methods

    @WithMockUser(roles= {"admin"})
    @Test
    public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
        mvc.perform(get("/employee/1").contentType(MediaType.APPLICATION_JSON))
          .andExpect(status().isOk());
    }
    //Repeated for other Paths
}