簡體   English   中英

測試彈簧安全站。 需要完全認證才能訪問此資源

[英]Testing spring security post. Full authentication is required to access this resource

我正在測試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-b​​ased-authentication

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM