测试弹簧安全帖。访问此资源需要完全身份验证

时间:2018-01-30 13:15:41

标签: java spring spring-boot testing

我正在测试Spring Security中的登录方法。我想得到200的状态,但是来了401。

@RunWith(SpringRunner.class)
@SpringBootTest
@DataJpaTest
@AutoConfigureMockMvc
public class AuthenticationTest {

@Autowired
private MockMvc mockMvc;

@Test
public void loginWithCorrectCredentials() throws Exception {
    RequestBuilder request = post("/api/login")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("username", "user")
            .param("password", "password");
    mockMvc.perform(request)
            .andExpect(status().isOk())
    .andExpect(cookie().exists("JSESSIONID"));
}

日志:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /api/login
   Parameters = {username=[user], password=[password]}
      Headers = {Content-Type=[application/x-www-form-urlencoded]}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 401
    Error message = Full authentication is required to access this resource
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains], WWW-Authenticate=[Basic realm="Spring"]}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-01-30 13:28:17.471  INFO 3988 --- [           main] o.s.t.c.transaction.TransactionContext   : Rolled back transaction for test context [DefaultTestContext@6ac13091 testClass = AuthenticationTest, testInstance = ua.com.kidspace.controller.AuthenticationTest@752b69e3, testMethod = loginWithCorrectCredentials@AuthenticationTest, testException = java.lang.AssertionError: Status expected:<200> but was:<401>, mergedContextConfiguration = [WebMergedContextConfiguration@5e316c74 testClass = AuthenticationTest, locations = '{}', classes = '{class ua.com.kidspace.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@6d2a209c key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@42607a4f, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@64485a47, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7276c8cd, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@306279ee, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@178398d7, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@24b1d79b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

java.lang.AssertionError: Status 
Expected :200
Actual   :401

我阅读了很多资源,但我无法修复“访问此资源需要完全身份验证”。添加了application.properties。如何解决这个问题?

security.user.password=password
security.user.name=username
management.security.enabled=false

我的配置WebSecurityConfig:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/api/login").permitAll()
            .antMatchers("/api/registration").permitAll()
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint())
            .and()
            .formLogin().successHandler(authenticationSuccessHandler)
            .loginPage("/api/login")
            .failureHandler(new SimpleUrlAuthenticationFailureHandler())
            .and()
            .logout()
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));

}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
}

@Bean
public UserDetailsService userDetailsService() {
    UserDetailsService userDetailsService = new UserDetailsServiceImpl();
    return userDetailsService;
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

}

1 个答案:

答案 0 :(得分:-1)

试试这个。

RequestBuilder request = post(formLogin()
        .user("username")
        .password("password"));

请参阅此处:https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/#testing-form-based-authentication