/** * Assert a cookie does not exist. Note that the existence check is * irrespective of whether max age is 0, i.e. expired. */ public ResultMatcher doesNotExist(final String name) { return result -> { Cookie cookie = result.getResponse().getCookie(name); assertTrue("Unexpected cookie with name '" + name + "'", cookie == null); }; }
private static Cookie getCookie(MvcResult result, String name) { Cookie cookie = result.getResponse().getCookie(name); if (cookie == null) { AssertionErrors.fail("No cookie with name '" + name + "'"); } return cookie; }
private MockCookie getCookie() { return (MockCookie) this.response.getCookie(this.cookieName); }
private Cookie getSessionCookie() { return this.response.getCookie("SESSION"); }
private static Cookie rememberMeCookie(MvcResult result) { return result.getResponse().getCookie("remember-me"); }
private String getSessionId() { return base64Decode(this.response.getCookie(this.cookieName).getValue()); }
@Test public void whenUserIsNotAuthenticated_clearsCurrentUserCookie() throws IOException, ServletException { when(currentUserCookieFactory.getNullCookie()).thenReturn(new Cookie("Current-User", null)); filter.doFilterInternal(req, res, filterChain); assertThat(res.getCookie("Current-User").getValue(), nullValue()); verify(filterChain).doFilter(req, res); }
@Test void silentAuthentication_clearsCurrentUserCookie_whenNotAuthenticated() throws Exception { MvcResult result = mockMvc.perform( get("/oauth/authorize?response_type=token&scope=openid&client_id=ant&prompt=none&redirect_uri=http://example.com/with/path.html") ).andReturn(); // This is necessary to make sure Current-User gets cleaned up when, for example, a UAA is restarted and the // user's JSESSIONID is no longer valid. assertThat(result.getResponse().getCookie("Current-User").getValue(), nullValue()); assertThat(result.getResponse().getCookie("Current-User").getMaxAge(), equalTo(0)); }
@Test public void whenUserIsAuthenticated_addsCurrentUserCookie() throws ServletException, IOException, CurrentUserCookieFactory.CurrentUserCookieEncodingException { UaaAuthentication authentication = new UaaAuthentication(new UaaPrincipal("user-guid", "marissa", "marissa@test.org", "uaa", "", ""), Collections.emptyList(), null); SecurityContextHolder.getContext().setAuthentication(authentication); when(currentUserCookieFactory.getCookie(any(UaaPrincipal.class))).thenReturn(new Cookie("Current-User", "current-user-cookie-value")); filter.doFilterInternal(req, res, filterChain); assertThat(res.getCookie("Current-User").getValue(), equalTo("current-user-cookie-value")); verify(filterChain).doFilter(req, res); }
@Test public void onDeleteSessionCookiePath() throws Exception { this.request.setContextPath("/somethingunique"); this.strategy.expireSession(this.request, this.response); Cookie sessionCookie = this.response.getCookie(this.cookieName); assertThat(sessionCookie.getPath()) .isEqualTo(this.request.getContextPath() + "/"); }
@Test public void onNewSessionCookiePath() throws Exception { this.request.setContextPath("/somethingunique"); this.strategy.setSessionId(this.request, this.response, this.session.getId()); Cookie sessionCookie = this.response.getCookie(this.cookieName); assertThat(sessionCookie.getPath()) .isEqualTo(this.request.getContextPath() + "/"); }
@Test public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { // @formatter:off MvcResult result = this.mockMvc .perform(formLogin()) .andReturn(); // @formatter:on Cookie cookie = result.getResponse().getCookie("SESSION"); assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); T session = this.sessions .findById(new String(Base64.getDecoder().decode(cookie.getValue()))); assertThat(session.getMaxInactiveInterval()) .isEqualTo(Duration.ofDays(30)); }
@Test public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { // @formatter:off MvcResult result = this.mockMvc .perform(formLogin()) .andReturn(); // @formatter:on Cookie cookie = result.getResponse().getCookie("SESSION"); assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); T session = this.sessions .findById(new String(Base64.getDecoder().decode(cookie.getValue()))); assertThat(session.getMaxInactiveInterval()) .isEqualTo(Duration.ofDays(30)); }
@Test public void setCookieHeaderValid() { response.addHeader(HttpHeaders.SET_COOKIE, "SESSION=123; Path=/; Secure; HttpOnly; SameSite=Lax"); Cookie cookie = response.getCookie("SESSION"); assertNotNull(cookie); assertTrue(cookie instanceof MockCookie); assertEquals("SESSION", cookie.getName()); assertEquals("123", cookie.getValue()); assertEquals("/", cookie.getPath()); assertTrue(cookie.getSecure()); assertTrue(cookie.isHttpOnly()); assertEquals("Lax", ((MockCookie) cookie).getSameSite()); }
private void validateCookie() { Cookie cookie = response.getCookie("Current-User"); assertNotNull(cookie); assertEquals(0, cookie.getMaxAge()); assertFalse(cookie.isHttpOnly()); }
@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 doFilterIsNewFalse() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { wrappedRequest.getSession(); } }); nextRequest(); this.response.reset(); doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { assertThat(wrappedRequest.getSession().isNew()).isFalse(); } }); assertThat(this.response.getCookie("SESSION")).isNull(); }
private Cookie getCookie(boolean isSecure) { CookieBasedCsrfTokenRepository repo = new CookieBasedCsrfTokenRepository(); repo.setSecure(isSecure); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); CsrfToken token = repo.generateToken(request); repo.saveToken(token, request, response); return response.getCookie(token.getParameterName()); } }
@Test public void csrfCookie_SecureIfRequestIsOverHttps() throws Exception { CookieBasedCsrfTokenRepository repo = new CookieBasedCsrfTokenRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setProtocol("https"); MockHttpServletResponse response = new MockHttpServletResponse(); CsrfToken token = repo.generateToken(request); repo.saveToken(token, request, response); Cookie cookie = response.getCookie(token.getParameterName()); assertTrue(cookie.getSecure()); }
@Test public void testSave_and_Load_Token() throws Exception { for (String contextPath : Arrays.asList("", "/uaa")) { String expectedCookiePath = contextPath + "/"; CookieBasedCsrfTokenRepository repo = new CookieBasedCsrfTokenRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setPathInfo("/login/somepath"); request.setContextPath(contextPath); CsrfToken token = repo.generateToken(request); assertTrue("The token is at least 22 characters long.", token.getToken().length() >= 22); repo.saveToken(token, request, response); Cookie cookie = response.getCookie(token.getParameterName()); assertNotNull(cookie); assertEquals(token.getToken(), cookie.getValue()); assertEquals(true, cookie.isHttpOnly()); assertEquals(repo.getCookieMaxAge(), cookie.getMaxAge()); assertNotNull(cookie.getPath()); assertEquals(expectedCookiePath, cookie.getPath()); request.setCookies(cookie); CsrfToken saved = repo.loadToken(request); assertEquals(token.getToken(), saved.getToken()); assertEquals(token.getHeaderName(), saved.getHeaderName()); assertEquals(token.getParameterName(), saved.getParameterName()); } }