java - 测试 spring 安全帖子。访问此资源需要完全身份验证

标签 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();
}

最佳答案

试试这个。

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

关于java - 测试 spring 安全帖子。访问此资源需要完全身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48522372/

相关文章:

java - 用Java模拟局域网?

java - 使用 Spring 框架在整个应用程序中保留一个对象

java - Android 2.3 设备的 EditText TextWatcher java.lang.NullPointerException

java - 尽管文件位于类路径中,但无法找到资源

spring - 部署生成的 Maven Spring 项目不起作用

java - Spring/JPA/persistence实体属性字段不能是final的?

java - 始终使用 jhipster 将日期保存到数据库中的今天日期

java - @Autowired HttpSession 不保存简单的字符串 - SpringBoot

Java串行数据事件处理

java - Spring MVC 中的延迟计算