I'm facing an issue authenticating my app under junit-test.
I've got a CustomAuthenticationProvider
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserRepository userRepository;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//businness logic
return auth;
}
}
A SecurityConfig, that uses it
@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
}
}
And my test, that is supposed to call on a Rest API and make sure, that answer is Ok.
@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);
}
}
Well, the test always failes, because GET returns 401, instead of 200. Can anyone help, what it wrong with SecurityContext?