[英]Why is Spring Security CSRF check failing when using MockMVC MockMvc
抱歉信息過載,我認為這里的信息比需要的多得多。
所以我有這個測試代碼
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() );
}
}
這是相關調試 output
[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
,因為它認為 session 無效。
我們使用 spring 引導父 BOM僅用於依賴管理,我們尚未轉換為 spring 引導(WIP)。 包含的信息讓您知道我們使用的是什么版本。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath />
</parent>
鑒於我正在使用 spring security user()
和springSecurity()
來設置 MockMvc,我不確定為什么 CSRF 不正確。 我將我的路徑添加到我們在檢查 CSRF 時排除的路徑中,這個問題就消失了。 我需要做什么才能通過 CSRF 檢查?
看起來您並沒有在測試中的任何地方為您的請求生成 CSRF 令牌。 日志確實顯示您那里有一些 CSRF 令牌,但如果您沒有在請求中提供此類令牌,CsrfFilter 將為您創建一個並與那個我希望以您報告的方式失敗的令牌進行比較。
您可以通過將SecurityMockMvcRequestPostProcessors.csrf()
作為mockMvc.perform(builder).with(... )
的參數來為 mockMvc 請求創建一個 csrf 令牌。
為了檢查您的請求中是否有 csrf 令牌,我將通過調試器運行它並在 CsrfFilter 的第 120-123 行周圍放置一個斷點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.