为什么使用mockmvc mockmvc时spring security csrf检查失败

ruarlubt  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(537)

很抱歉信息过载,我认为这里的信息比需要的多得多。
所以我有这个测试代码

package com.myapp.ui.controller.user;

import static com.myapp.ui.controller.user.PasswordResetController.PASSWORD_RESET_PATH;
import static com.myapp.ui.controller.user.PasswordResetController.ResetPasswordAuthenticatedDto;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myapp.db.liquibase.LiquibaseService;
import com.myapp.sample.ModelBuilderFactory;

@ComponentScan( "com.myapp.ui")
@SpringJUnitWebConfig(  classes = { LiquibaseService.class, ControllerTestBaseConfig.class }  )
public class PasswordResetControllerTest  {

    @Autowired
    private ModelBuilderFactory mbf;

    private final ObjectMapper mapper = new ObjectMapper();
    private MockMvc mockMvc;
    private String username;

    @BeforeEach
    void setup( WebApplicationContext wac) throws Exception {
        username = mbf.siteUser().get().getUsername();
        this.mockMvc = MockMvcBuilders.webAppContextSetup( wac )
            .apply( SecurityMockMvcConfigurers.springSecurity() )
            .defaultRequest( get( "/" ).with( user(username) ) )
            .alwaysDo( print() )
            .build();
    }

    @ParameterizedTest
    @NullAndEmptySource
    @ValueSource(strings = "abcd")
    void testPasswordResetInvalidate( String password ) throws Exception {
        ResetPasswordAuthenticatedDto dto = new ResetPasswordAuthenticatedDto( username, password );

        RequestBuilder builder = MockMvcRequestBuilders.patch( PASSWORD_RESET_PATH )
            .contentType( MediaType.APPLICATION_JSON )
            .content( mapper.writer().writeValueAsString( dto ) );

        mockMvc.perform( builder )
            .andExpect( MockMvcResultMatchers.status().isNoContent() );
    }

}

这是相关的调试输出

[INFO ] PATCH /ui/authn/user/password-reset for user null (session 1, csrf f47a7f39-c310-4e5d-a4be-cc9bd120229f) with session cookie (null) will be validated against CSRF [main] com.myapp.config.MyCsrfRequestMatcher.matches(MyCsrfRequestMatcher.java:76) 
[DEBUG] Invalid CSRF token found for http://localhost/ui/authn/user/password-reset            [main] org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:127) 
[DEBUG] Starting new session (if required) and redirecting to '/login?error=timeout'          [main] org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy.onInvalidSessionDetected(SimpleRedirectInvalidSessionStrategy.java:49) 
[DEBUG] Redirecting to '/login?error=timeout'                                                 [main] org.springframework.security.web.DefaultRedirectStrategy.sendRedirect(DefaultRedirectStrategy.java:54) 
[DEBUG] Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@4b367665 [main] org.springframework.security.web.header.writers.HstsHeaderWriter.writeHeaders(HstsHeaderWriter.java:169) 
[DEBUG] SecurityContextHolder now cleared, as request processing completed                    [main] org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:119) 

MockHttpServletRequest:
      HTTP Method = PATCH
      Request URI = /ui/authn/user/password-reset
       Parameters = {}
          Headers = [Content-Type:"application/json", Content-Length:"68"]
             Body = <no character encoding set>
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@55b1156b, SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@12919b87: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@12919b87: Principal: org.springframework.security.core.userdetails.User@1e05232c: Username: lab_admin4oyc8tkytxu4zllguk-1qg; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER}

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 = 302
    Error message = null
          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:"SAMEORIGIN", Location:"/login?error=timeout"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = /login?error=timeout
          Cookies = []

java.lang.AssertionError: Status expected:<204> but was:<302>
Expected :204
Actual   :302

这是我们的关系 SecurityConfig ```
@Override
protected void configure( HttpSecurity http ) throws Exception {

    ApplicationContext ctx = getApplicationContext();
    http
        .addFilterAfter( ctx.getBean( TimeoutFilter.class ), SecurityContextPersistenceFilter.class )
        .addFilterAt( ctx.getBean( "myLogoutFilter", LogoutFilter.class ), LogoutFilter.class )
        .addFilterBefore( ctx.getBean( IpAddressAuditFilter.class ), FilterSecurityInterceptor.class )
        .addFilterAt( ctx.getBean( MyConcurrentSessionFilter.class ), ConcurrentSessionFilter.class )
        .addFilterAfter( ctx.getBean( RequestLogFilter.class ), FilterSecurityInterceptor.class )
        .headers().xssProtection().and().frameOptions().sameOrigin().and()
        .authorizeRequests()
        .antMatchers(
            HttpMethod.GET,
            "/styles/**.css",
            "/fonts/**",
            "/scripts/**.js",
            "/VAADIN/**",
            "/jsp/**",
            "/*.css",
            "/help/**",
            "/public/error/**"
        ).permitAll()
        .antMatchers( "/app/**", "/downloads/**", "/ui/authn/**" ).fullyAuthenticated()
        .antMatchers(
            "/login**",
            "/register/**",
            "/public/**",
            "/sso_logout",
            "/sso_auth_failure",
            "/sso_concurrent_session",
            "/sso_timeout"
        ).anonymous()
        .anyRequest().denyAll()
        .and()
        .formLogin()
        .loginPage( "/login" )
        .loginProcessingUrl( SecurityConstants.loginPath() )
        .defaultSuccessUrl( "/app", true )
        .failureUrl( "/login?error=badCredentials" )
        .usernameParameter( SecurityConstants.usernameField() )
        .passwordParameter( SecurityConstants.passwordField())
        .permitAll()
        .and()
        .exceptionHandling()
        .accessDeniedHandler( new MyAccessDeniedHandler() )
        .authenticationEntryPoint( new LoginUrlAuthenticationEntryPoint( "/login" ) )
        .and()
        .csrf().requireCsrfProtectionMatcher( csrfRequestMatcher )
        .and()
        .sessionManagement().sessionFixation().newSession().invalidSessionUrl( "/login?error=timeout" )
        .maximumSessions( 1 ).sessionRegistry( sessionRegistry )
        .expiredUrl( "/login?error=concurrentSession"  );
}
测试正在重定向到 `timeout` 因为它认为会话无效。
我们将springboot父bom仅用于依赖关系管理,尚未转换为springboot(wip)。包括的信息让你知道我们的版本。
ffdz8vbo

ffdz8vbo1#

在测试的任何地方,看起来都没有为请求生成csrf令牌。日志确实显示您在那里有一些csrf令牌,但是如果您没有在请求中提供这样的令牌,csrffilter将创建一个,并与该令牌进行比较,我预计会以您报告的方式失败。
您可以为mockmvc请求创建一个csrf令牌,方法是 SecurityMockMvcRequestPostProcessors.csrf() 作为的参数 mockMvc.perform(builder).with( ... ) .
为了检查您的请求中是否有csrf令牌,我将通过一个调试器运行它,并在csrffilter的第120-123行周围放置一个断点。

相关问题