我试图熟悉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”限制为管理员。
答案 0 :(得分:1)
您当前的配置将仅限制employee
下的所有路径,例如employee/1
,而不是/employee
。此外,返回到employee
时,您没有对authorizeRequests
匹配器执行任何操作,然后将anyRequest
配置为角色ADMIN
将employee
及其下面的任何路径限制为ADMIN
。
http.authorizeRequests().antMatchers("/employee**", "/employee/**").hasRole("ADMIN").httpBasic();
使用**
将捕获路径中的目录。
请参见
和
使用/ **或**的模式值被视为通用匹配,它将匹配任何请求。以/ **结尾的模式(没有其他通配符)通过使用子字符串匹配进行优化-/ 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
}