Spring Boot Security-蚂蚁匹配器不起作用

时间:2019-08-12 08:28:25

标签: spring-boot spring-security roles

我试图熟悉Spring Boot的安全性,我的API是对127.0.0.1:8080/employee/的简单GET / POST 像这样简单的自动配置。

@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禁止。 尝试过: antMatcher(“ / employee *”),但适用于任何用户。在了解这种模式的工作方式时,我可以得到一些帮助吗,我只需要将“ / employee”或“ / employee /”或“ / employee / 1”限制为管理员。

1 个答案:

答案 0 :(得分:1)

您当前的配置将仅限制employee下的所有路径,例如employee/1,而不是/employee。此外,返回到employee时,您没有对authorizeRequests匹配器执行任何操作,然后将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

  

使用/ **或**的模式值被视为通用匹配,它将匹配任何请求。以/ **结尾的模式(没有其他通配符)通过使用子字符串匹配进行优化-/ aaa / **模式将匹配/ aaa,/ aaa /和任何子目录,例如/ aaa / bbb / cc。

我还建议您通过@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
}