Ich habe ein Problem mit der Authentifizierung meiner App unter Junit-Test.Junit authenticate SpringRest schlägt fehl
ich 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 haben, dass es
@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
}
}
Und mein Test verwendet, das auf einer REST-API aufrufen soll, und stellen Sie sicher, dass Antwort 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);
}
}
Nun, der Test immer Failes, weil GET 401 zurückkehrt, statt 200. Kann mir jemand helfen, was es falsch mit Security?
@pvpkiran, autowiring failes mit Ausnahme für Abhängigkeits Keine qualifizierenden Bean vom Typ [org.springframework.security.core.context.SecurityContext]. – Ermintar
SecurityContextHolder.getContext(). SetAuthentication (Benutzer); funktioniert auch nicht – Ermintar