我已在BasicAuth
应用程序中实施SpringBoot
来验证几个网址。有点像:
配置类
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${auth.authenticated}")
private String[] allAuthenticated;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(allAuthenticated).authenticated()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
// .... Rest of the code
}
application.yml
auth.authenticated: /onlineshop/v1/ecart,/onlineshop/v1/wishlist
工作正常,但我想对此进行单元测试。
我在考虑一个简单的测试用例,我可以直接向/onlineshop/v1/ecart
或/onlineshop/v1/wishlist
发出HTTP请求,并以某种方式检查它们是否经过身份验证。
我遇到了这个MockMVC section,编码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=WebSecurityConfig.class)
public class BasicAuthTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity()) 1
.build();
}
@Test
public void shouldBeAuthenticated() throws Exception {
mvc.perform(get("/onlineshop/v1/ecart").with(httpBasic("user","password"))).andExpect(status().isOk());
}
}
但每次它都给我404错误。所以我不确定我是否正确配置了它或者是什么?
如果还有其他更好的方法来测试BasicAuth,请提出建议。
谢谢