【发布时间】:2017-10-03 23:37:35
【问题描述】:
我在 junit-test 下验证我的应用时遇到问题。
我有一个 CustomAuthenticationProvider
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserRepository userRepository;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//businness logic
return auth;
}
}
使用它的 SecurityConfig
@Configuration
@EnableWebSecurity
@Import(CustomAuthenticationProvider.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//some permission filters here
}
}
我的测试应该调用 Rest API 并确保答案是好的。
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@SpringApplicationConfiguration(classes = {MyApplication.class},locations = {"/dbContext.xml"})
@TestPropertySource("/application.properties")
@WebIntegrationTest
public class SimpleTest {
@Autowired
protected WebApplicationContext webAppContext;
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Before
public void setup() {
RestAssuredMockMvc.webAppContextSetup(webAppContext);
SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication user = customAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken("admin", "123"));
context.setAuthentication(user);
SecurityContextHolder.setContext(context);
}
@Test
public void makeSureLoginIsOk() {
given().when().get("/myurl").then().statusCode(200);
}
}
好吧,测试总是失败,因为 GET 返回 401,而不是 200。 谁能帮忙,SecurityContext有什么问题?
【问题讨论】:
-
@pvpkiran,自动装配失败,出现异常没有为依赖找到类型 [org.springframework.security.core.context.SecurityContext] 的合格 bean。
-
SecurityContextHolder.getContext().setAuthentication(user);也不行
标签: java spring spring-boot junit spring-security