@Test public void cookie() { Cookie cookie1 = new Cookie("foo", "bar"); Cookie cookie2 = new Cookie("baz", "qux"); this.builder.cookie(cookie1, cookie2); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Cookie[] cookies = request.getCookies(); assertEquals(2, cookies.length); assertEquals("foo", cookies[0].getName()); assertEquals("bar", cookies[0].getValue()); assertEquals("baz", cookies[1].getName()); assertEquals("qux", cookies[1].getValue()); }
@Test public void mergeCookie() throws Exception { String cookieName = "PARENT"; String cookieValue = "VALUE"; MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()) .defaultRequest(get("/").cookie(new Cookie(cookieName, cookieValue))) .build(); Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies(); assertThat(cookies, notNullValue()); assertThat(cookies.length, equalTo(1)); Cookie cookie = cookies[0]; assertThat(cookie.getName(), equalTo(cookieName)); assertThat(cookie.getValue(), equalTo(cookieValue)); }
@Test public void requestWithRememberMeWhenUsingCustomUserDetailsServiceThenInvokesThisUserDetailsService() throws Exception { this.spring.configLocations(this.xml("WithUserDetailsService")).autowire(); UserDetailsService userDetailsService = this.spring.getContext().getBean(UserDetailsService.class); when(userDetailsService.loadUserByUsername("user")).thenAnswer((invocation) -> new User("user", "{noop}password", Collections.emptyList())); MvcResult result = this.rememberAuthentication("user", "password").andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); verify(userDetailsService, atLeastOnce()).loadUserByUsername("user"); }
@Test public void requestWithRememberMeWhenUsingAuthenticationSuccessHandlerThenInvokesHandler() throws Exception { this.spring.configLocations(this.xml("WithAuthenticationSuccessHandler")).autowire(); TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); template.execute(CREATE_TABLE_SQL); MvcResult result = this.rememberAuthentication("user", "password") .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(redirectedUrl("/target")); int count = template.queryForObject("select count(*) from persistent_logins", int.class); assertThat(count).isEqualTo(1); }
@Test public void requestWithRememberMeWhenUsingCustomDataSourceThenAutomaticallyReauthenticates() throws Exception { this.spring.configLocations(this.xml("WithDataSource")).autowire(); TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); template.execute(CREATE_TABLE_SQL); MvcResult result = this.rememberAuthentication("user", "password") .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); int count = template.queryForObject("select count(*) from persistent_logins", int.class); assertThat(count).isEqualTo(1); }
request.cookie(servletCookie);
@Test public void requestWithRememberMeWhenUsingCustomTokenRepositoryThenAutomaticallyReauthenticates() throws Exception { this.spring.configLocations(this.xml("WithTokenRepository")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); JdbcTemplate template = this.spring.getContext().getBean(JdbcTemplate.class); int count = template.queryForObject("select count(*) from persistent_logins", int.class); assertThat(count).isEqualTo(1); }
@Test void testLogin_Csrf_Reset_On_Refresh() throws Exception { MvcResult mvcResult = mockMvc .perform( get("/login")) .andReturn(); Cookie csrf1 = mvcResult.getResponse().getCookie(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); mvcResult = mockMvc .perform( get("/login") .cookie(csrf1)) .andReturn(); Cookie csrf2 = mvcResult.getResponse().getCookie(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME); assertNotNull(csrf2); assertNotEquals(csrf1.getValue(), csrf2.getValue()); }
@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 requestWithRememberMeWhenTokenValidityIsConfiguredThenCookieReflectsCorrectExpiration() throws Exception { this.spring.configLocations(this.xml("TokenValidity")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 10000)) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); }
@Test public void requestWithRememberMeWhenUsingCustomRememberMeServicesThenAuthenticates() throws Exception { // SEC-1281 - using key with external services this.spring.configLocations(this.xml("WithServicesRef")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 5000)) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); // SEC-909 this.mvc.perform(post("/logout") .cookie(cookie) .with(csrf())) .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)) .andReturn(); }
/** * SEC-742 */ @Test public void requestWithRememberMeWhenExcludingBasicAuthenticationFilterThenStillReauthenticates() throws Exception { this.spring.configLocations(this.xml("Sec742")).autowire(); MvcResult result = this.mvc.perform(login("user", "password") .param("remember-me", "true") .with(csrf())) .andExpect(redirectedUrl("/messageList.html")) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); }
/** * SEC-2119 */ @Test public void requestWithRememberMeWhenUsingCustomRememberMeParameterThenReauthenticates() throws Exception { this.spring.configLocations(this.xml("WithRememberMeParameter")).autowire(); MvcResult result = this.mvc.perform(login("user", "password") .param("custom-remember-me-parameter", "true") .with(csrf())) .andExpect(redirectedUrl("/")) .andReturn(); Cookie cookie = rememberMeCookie(result); this.mvc.perform(get("/authenticated") .cookie(cookie)) .andExpect(status().isOk()); }
@Test void accountChooserEnabled( @Autowired IdentityZoneProvisioning identityZoneProvisioning ) throws Exception { String clientName = "woohoo"; IdentityZoneConfiguration config = new IdentityZoneConfiguration(); config.setIdpDiscoveryEnabled(true); config.setAccountChooserEnabled(true); IdentityZone zone = setupZone(webApplicationContext, mockMvc, identityZoneProvisioning, generator, config); MockHttpSession session = new MockHttpSession(); String clientId = generator.generate(); BaseClientDetails client = new BaseClientDetails(clientId, "", "", "client_credentials", "uaa.none", "http://*.wildcard.testing,http://testing.com"); client.setClientSecret("secret"); client.addAdditionalInformation(ClientConstants.CLIENT_NAME, clientName); MockMvcUtils.createClient(webApplicationContext, client, zone); SavedAccountOption savedAccount = new SavedAccountOption(); savedAccount.setEmail("test@example.org"); savedAccount.setOrigin("uaa"); savedAccount.setUserId("1234-5678"); savedAccount.setUsername("test@example.org"); mockMvc.perform(get("/login") .session(session) .cookie(new Cookie("Saved-Account-12345678", URLEncoder.encode(JsonUtils.writeValueAsString(savedAccount)))) .header("Accept", TEXT_HTML) .with(new SetServerNameRequestPostProcessor(zone.getSubdomain() + ".localhost"))) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("idp_discovery/account_chooser")); }
.param("password", "secret") .session(session) .cookie(cookie) .param(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, "csrf1"); mockMvc.perform(invalidPost) .param("password_confirmation", passwordPolicyWithInvalidPassword.password) .session(session) .cookie(cookie) .with(cookieCsrf()); mockMvc.perform(validPost)
@Test public void requestWithCookies() throws Exception { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo").cookie( new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), new javax.servlet.http.Cookie("cookieName2", "cookieVal2"))); assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); assertThat(request.getCookies().size()).isEqualTo(2); Iterator<RequestCookie> cookieIterator = request.getCookies().iterator(); RequestCookie cookie1 = cookieIterator.next(); assertThat(cookie1.getName()).isEqualTo("cookieName1"); assertThat(cookie1.getValue()).isEqualTo("cookieVal1"); RequestCookie cookie2 = cookieIterator.next(); assertThat(cookie2.getName()).isEqualTo("cookieName2"); assertThat(cookie2.getValue()).isEqualTo("cookieVal2"); }
@Test public void curlSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON) .cookie(new Cookie("cookieName", "cookieVal"))).andExpect(status().isOk()) .andDo(document("curl-snippet-with-cookies")); assertThat(new File( "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") .withContent(String.format( "$ curl 'http://localhost:8080/' -i -X GET \\%n" + " -H 'Accept: application/json' \\%n" + " --cookie 'cookieName=cookieVal'")))); }
@Test public void httpieSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON) .cookie(new Cookie("cookieName", "cookieVal"))).andExpect(status().isOk()) .andDo(document("httpie-snippet-with-cookies")); assertThat(new File( "build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc")) .has(content(codeBlock(TemplateFormats.asciidoctor(), "bash") .withContent(String .format("$ http GET 'http://localhost:8080/' \\%n" + " 'Accept:application/json' \\%n" + " 'Cookie:cookieName=cookieVal'")))); }