@Test public void logoutWhenSpecifyingCookiesToDeleteThenSetCookieAdded() throws Exception { this.spring.configLocations(xml("DeleteCookies")).autowire(); MvcResult result = this.mvc.perform(post("/logout").with(csrf())).andReturn(); List<String> values = result.getResponse().getHeaders("Set-Cookie"); assertThat(values.size()).isEqualTo(2); assertThat(values).extracting(value -> value.split("=")[0]).contains("JSESSIONID", "mycookie"); }
private static RequestBuilder formLogin(MockHttpSession session) { return post("/login") .param("username", "user") .param("password", "password") .session(session) .with(csrf()); } }
@Test public void requestWhenCreateSessionIsSetToIfRequiredThenCreatesSessionOnLogin() throws Exception { this.spring.configLocations(this.xml("CreateSessionIfRequired")).autowire(); ServletContext servletContext = this.mvc.getDispatcherServlet().getServletContext(); MockHttpServletRequest request = post("/login") .param("username", "user") .param("password", "password") .buildRequest(servletContext); request = csrf().postProcessRequest(request); MockHttpServletResponse response = request(request, this.spring.getContext()); assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_MOVED_TEMPORARILY); assertThat(request.getSession(false)).isNotNull(); }
private ResultActions rememberAuthentication(String username, String password) throws Exception { return this.mvc.perform(login(username, password) .param(DEFAULT_PARAMETER, "true") .with(csrf())) .andExpect(redirectedUrl("/")); }
@Test public void requestWhenBearerTokenResolverAllowsRequestBodyAndRequestContainsTwoTokensThenInvalidRequest() throws Exception { this.spring.register(AllowBearerTokenInRequestBodyConfig.class, JwtDecoderConfig.class, BasicController.class).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); when(decoder.decode(anyString())).thenReturn(JWT); this.mvc.perform(post("/authenticated") .param("access_token", JWT_TOKEN) .with(bearerToken(JWT_TOKEN)) .with(csrf())) .andExpect(status().isBadRequest()) .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("invalid_request"))); }
@Test public void requestWhenCreateSessionIsSetToNeverThenDoesNotCreateSessionOnLogin() throws Exception { this.spring.configLocations(this.xml("CreateSessionNever")).autowire(); MockHttpServletRequest request = post("/login") .param("username", "user") .param("password", "password") .buildRequest(this.servletContext()); request = csrf().postProcessRequest(request); MockHttpServletResponse response = request(request, this.spring.getContext()); assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_MOVED_TEMPORARILY); assertThat(request.getSession(false)).isNull(); }
@Test public void logoutWhenSpecifyingSuccessHandlerRefThenResponseHandledAccordingly() throws Exception { this.spring.configLocations(xml("LogoutSuccessHandlerRef")).autowire(); this.mvc.perform(post("/logout").with(csrf())) .andExpect(redirectedUrl("/logoutSuccessEndpoint")); }
@Test public void authenticateWhenDefaultTargetUrlConfiguredThenRedirectsAccordingly() throws Exception { this.spring.configLocations(this.xml("WithDefaultTargetUrl")).autowire(); this.mvc.perform(post("/login") .param("username", "user") .param("password", "password") .with(csrf())) .andExpect(redirectedUrl("/default")); }
@Test public void authenticateWhenCustomHandlerBeansConfiguredThenInvokesAccordingly() throws Exception { this.spring.configLocations(this.xml("WithSuccessAndFailureHandlers")).autowire(); this.mvc.perform(post("/login") .param("username", "user") .param("password", "password") .with(csrf())) .andExpect(status().isIAmATeapot()); this.mvc.perform(post("/login") .param("username", "user") .param("password", "wrong") .with(csrf())) .andExpect(status().isIAmATeapot()); }
@Test public void authenticateWhenCustomUsernameAndPasswordParametersThenSucceeds() throws Exception { this.spring.configLocations(this.xml("WithUsernameAndPasswordParameters")).autowire(); this.mvc.perform(post("/login") .param("xname", "user") .param("xpass", "password") .with(csrf())) .andExpect(redirectedUrl("/")); }
/** * SEC-3147: authentication-failure-url should be contained "error" parameter if login-page="/login" */ @Test public void authenticateWhenLoginPageIsSlashLoginAndAuthenticationFailsThenRedirectContainsErrorParameter() throws Exception { this.spring.configLocations(this.xml("ForSec3147")).autowire(); this.mvc.perform(post("/login") .param("username", "user") .param("password", "wrong") .with(csrf())) .andExpect(redirectedUrl("/login?error")); }
@Test public void logoutWhenUsingRememberMeDefaultsThenCookieIsCancelled() throws Exception { this.spring.configLocations(this.xml("DefaultConfig")).autowire(); MvcResult result = this.rememberAuthentication("user", "password").andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(post("/logout") .cookie(cookie) .with(csrf())) .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)); }
@Test public void requestWhenCreateSessionIsSetToStatelessThenDoesNotCreateSessionOnLogin() throws Exception { this.spring.configLocations(this.xml("CreateSessionStateless")).autowire(); this.mvc.perform(post("/login") .param("username", "user") .param("password", "password") .with(csrf())) .andExpect(status().isFound()) .andExpect(session().exists(false)); }
/** * http/logout custom */ @Test @WithMockUser public void logoutWhenUsingVariousCustomizationsMatchesNamespace() throws Exception { this.spring.register(CustomHttpLogoutConfig.class).autowire(); this.mvc.perform(post("/custom-logout").with(csrf())) .andExpect(authenticated(false)) .andExpect(redirectedUrl("/logout-success")) .andExpect(result -> assertThat(result.getResponse().getCookies()).hasSize(1)) .andExpect(cookie().maxAge("remove", 0)) .andExpect(session(Objects::nonNull)); }
/** * http/logout equivalent */ @Test @WithMockUser public void logoutWhenUsingDefaultsThenMatchesNamespace() throws Exception { this.spring.register(HttpLogoutConfig.class).autowire(); this.mvc.perform(post("/logout").with(csrf())) .andExpect(authenticated(false)) .andExpect(redirectedUrl("/login?logout")) .andExpect(noCookies()) .andExpect(session(Objects::isNull)); }
/** * http/logout@success-handler-ref */ @Test @WithMockUser public void logoutWhenUsingSuccessHandlerRefThenMatchesNamespace() throws Exception { this.spring.register(SuccessHandlerRefHttpLogoutConfig.class).autowire(); this.mvc.perform(post("/logout").with(csrf())) .andExpect(authenticated(false)) .andExpect(redirectedUrl("/SuccessHandlerRefHttpLogoutConfig")) .andExpect(noCookies()) .andExpect(session(Objects::isNull)); }
@Test @WithMockUser public void postWhenCsrfMismatchesThenForbidden() throws Exception { this.spring.configLocations( this.xml("shared-controllers"), this.xml("AutoConfig") ).autowire(); MvcResult result = this.mvc.perform(get("/ok")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); this.mvc.perform(post("/ok") .session(session) .with(csrf().useInvalidToken())) .andExpect(status().isForbidden()); }
@Test public void requestWhenUsingMutuallyExclusiveHttpElementsThenIsRoutedAccordingly() throws Exception { this.spring.configLocations(this.xml("DistinctHttpElements")).autowire(); this.mvc.perform(MockMvcRequestBuilders.get("/first") .with(httpBasic("user", "password"))) .andExpect(status().isOk()); this.mvc.perform(post("/second/login") .param("username", "user") .param("password", "password") .with(csrf())) .andExpect(status().isFound()) .andExpect(redirectedUrl("/")); }
@Test public void logoutWhenDefaultConfigurationThenCsrfCleared() throws Exception { this.spring.configLocations( this.xml("shared-controllers"), this.xml("AutoConfig") ).autowire(); MvcResult result = this.mvc.perform(get("/csrf")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); this.mvc.perform(post("/logout").session(session) .with(csrf())) .andExpect(status().isFound()); this.mvc.perform(get("/csrf").session(session)) .andExpect(csrfChanged(result)); }
@Test public void requestWhenInterceptUrlMatchesMethodAndRequiresHttpsThenSecuresAccordingly() throws Exception { this.spring.configLocations(xml("InterceptUrlMethodRequiresHttps")).autowire(); this.mvc.perform(post("/protected").with(csrf())) .andExpect(status().isOk()); this.mvc.perform(get("/protected") .secure(true) .with(httpBasic("user", "password"))) .andExpect(status().isForbidden()); this.mvc.perform(get("/protected") .secure(true) .with(httpBasic("admin", "password"))) .andExpect(status().isOk()); }