Java Code Examples for org.springframework.mock.web.mockhttpservletrequest#setCookies()

The following examples show how to use org.springframework.mock.web.mockhttpservletrequest#setCookies() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApmFilterTest.java    From apm-agent-java with Apache License 2.0 8 votes vote down vote up
@Test
void testNoHeaderRecording() throws IOException, ServletException {
    when(coreConfiguration.isCaptureHeaders()).thenReturn(false);
    filterChain = new MockFilterChain(new TestServlet());
    final MockHttpServletRequest get = new MockHttpServletRequest("GET", "/foo");
    get.addHeader("Elastic-Apm-Traceparent", "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01");
    get.setCookies(new Cookie("foo", "bar"));
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    mockResponse.addHeader("foo", "bar");
    mockResponse.addHeader("bar", "baz");
    filterChain.doFilter(get, mockResponse);
    assertThat(reporter.getTransactions()).hasSize(1);
    assertThat(reporter.getFirstTransaction().getContext().getResponse().getHeaders().isEmpty()).isTrue();
    assertThat(reporter.getFirstTransaction().getContext().getRequest().getHeaders().isEmpty()).isTrue();
    assertThat(reporter.getFirstTransaction().getContext().getRequest().getCookies().isEmpty()).isTrue();
    assertThat(reporter.getFirstTransaction().getTraceContext().getTraceId().toString()).isEqualTo("0af7651916cd43dd8448eb211c80319c");
    assertThat(reporter.getFirstTransaction().getTraceContext().getParentId().toString()).isEqualTo("b9c7c989f97918e1");
}
 
Example 2
Source File: ApiListenerServletTest.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieAuthentication200() throws ServletException, IOException, ListenerException, ConfigurationException {
	String uri = "cookie";
	addListener(uri, Methods.POST, AuthMethods.COOKIE);
	String authToken = "random-token_thing";

	ApiPrincipal principal = new ApiPrincipal();
	assertTrue("principal is not logged in? ttl expired?", principal.isLoggedIn());
	ApiCacheManager.getInstance().put(authToken, principal);

	Map<String, String> headers = new HashMap<String, String>();
	MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers);
	Cookie cookies = new Cookie("authenticationToken", authToken);
	request.setCookies(cookies);
	Response result = service(request);

	String sessionAuthToken = (String) session.get("authorizationToken");
	assertNotNull("session should contain auth token", sessionAuthToken);
	assertEquals("auth tokens should match", authToken, sessionAuthToken);

	assertEquals(200, result.getStatus());
	assertTrue(result.containsHeader("Allow"));
	assertNull(result.getErrorMessage());
	assertTrue("response contains auth cookie", result.containsCookie("authenticationToken"));
}
 
Example 3
Source File: GrafanaUserDetailsTest.java    From Insights with Apache License 2.0 6 votes vote down vote up
@Test(priority = 1)
public void testGetUserDetails() throws Exception {

	MockHttpServletRequest request = new MockHttpServletRequest();

	request.setCookies(userDetailsTestData.cookies);
	request.addHeader("Accept", userDetailsTestData.accept);
	request.addHeader("Authorization", userDetailsTestData.authorization);
	request.addHeader("Content-Type", userDetailsTestData.contentType);
	request.addHeader("Origin", userDetailsTestData.origin);
	request.addHeader("Referer", userDetailsTestData.referer);
	request.addHeader("XSRF-TOKEN", userDetailsTestData.XSRFTOKEN);

	UserDetails Actualrespone = GrafanaUserDetailsUtil.getUserDetails(request);

}
 
Example 4
Source File: GenerateServiceTicketActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceTicketFromCookie() throws Exception {
    MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    context.getFlowScope().put("ticketGrantingTicketId", this.ticketGrantingTicket);
    MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.setCookies(new Cookie[] {new Cookie("TGT",
            this.ticketGrantingTicket)});

    this.action.execute(context);

    assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
 
Example 5
Source File: OAuth2AuthenticationServiceTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testSessionExpired() {
    MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com");
    Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE);
    Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.SESSION_TOKEN_COOKIE, EXPIRED_SESSION_TOKEN_VALUE);
    request.setCookies(accessTokenCookie, refreshTokenCookie);
    MockHttpServletResponse response = new MockHttpServletResponse();
    HttpServletRequest newRequest = refreshTokenFilter.refreshTokensIfExpiring(request, response);
    //cookies in response are deleted
    Cookie newAccessTokenCookie = response.getCookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE);
    Assert.assertEquals(0, newAccessTokenCookie.getMaxAge());
    Cookie newRefreshTokenCookie = response.getCookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE);
    Assert.assertEquals(0, newRefreshTokenCookie.getMaxAge());
    //request no longer contains cookies
    Cookie requestAccessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(newRequest);
    Assert.assertNull(requestAccessTokenCookie);
    Cookie requestRefreshTokenCookie = OAuth2CookieHelper.getRefreshTokenCookie(newRequest);
    Assert.assertNull(requestRefreshTokenCookie);
}
 
Example 6
Source File: CsrfPreventionFilterTest.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
protected MockHttpServletResponse performModifyingRequest(String token, MockHttpSession session) throws IOException, ServletException {
  MockHttpServletResponse response = new MockHttpServletResponse();

  MockHttpServletRequest modifyingRequest = new MockHttpServletRequest();
  modifyingRequest.setMethod("POST");
  modifyingRequest.setSession(session);
  modifyingRequest.setRequestURI(SERVICE_PATH  + modifyingRequestUrl);
  modifyingRequest.setContextPath(SERVICE_PATH);

  modifyingRequest.addHeader(CSRF_HEADER_NAME, token);
  Cookie[] cookies = {new Cookie(CSRF_COOKIE_NAME, token)};
  modifyingRequest.setCookies(cookies);

  applyFilter(modifyingRequest, response);

  return response;
}
 
Example 7
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySsoSessionCookieOnServiceSsoDisallowed() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();

    final WebApplicationService svc = mock(WebApplicationService.class);
    when(svc.getId()).thenReturn("TestSsoFalse");

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");
    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    this.context.getFlowScope().put("service", svc);
    this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(0, response.getCookies().length);
}
 
Example 8
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifySsoSessionCookieOnRenewAsParameter() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(CasProtocolConstants.PARAMETER_RENEW, "true");

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");
    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    this.action.setCreateSsoSessionCookieOnRenewAuthentications(false);
    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(0, response.getCookies().length);
}
 
Example 9
Source File: RequestProcessorTest.java    From auth0-java-mvc-common with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnProcessIfCodeRequestFailsToExecuteCodeExchange() throws Exception {
    exception.expect(IdentityVerificationException.class);
    exception.expect(IdentityVerificationExceptionMatcher.hasCode("a0.api_error"));
    exception.expectMessage("An error occurred while exchanging the authorization code.");


    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));

    AuthRequest codeExchangeRequest = mock(AuthRequest.class);
    when(codeExchangeRequest.execute()).thenThrow(Auth0Exception.class);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);

    RequestProcessor handler = new RequestProcessor(client, "code", verifyOptions, tokenVerifier, true);
    handler.process(request, response);
}
 
Example 10
Source File: ApmFilterTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testAllHeaderRecording() throws IOException, ServletException {
    when(coreConfiguration.isCaptureHeaders()).thenReturn(true);
    filterChain = new MockFilterChain(new TestServlet());
    final MockHttpServletRequest get = new MockHttpServletRequest("GET", "/foo");
    get.addHeader("foo", "bar");
    get.setCookies(new Cookie("foo", "bar"));
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    mockResponse.addHeader("foo", "bar");
    mockResponse.addHeader("bar", "baz");
    filterChain.doFilter(get, mockResponse);
    assertThat(reporter.getTransactions()).hasSize(1);
    final Request request = reporter.getFirstTransaction().getContext().getRequest();
    assertThat(request.getHeaders().isEmpty()).isFalse();
    assertThat(request.getHeaders().get("foo")).isEqualTo("bar");
    assertThat(request.getCookies().get("foo")).isEqualTo("bar");
    final Response response = reporter.getFirstTransaction().getContext().getResponse();
    assertThat(response.getHeaders().get("foo")).isEqualTo("bar");
    assertThat(response.getHeaders().get("bar")).isEqualTo("baz");
}
 
Example 11
Source File: RequestProcessorTest.java    From auth0-java-mvc-common with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnProcessIfIdTokenRequestDoesNotPassIdTokenVerification() throws Exception {
    exception.expect(IdentityVerificationException.class);
    exception.expect(IdentityVerificationExceptionMatcher.hasCode("a0.invalid_jwt_error"));
    exception.expectMessage("An error occurred while trying to verify the ID Token.");

    doThrow(TokenValidationException.class).when(tokenVerifier).verify(eq("frontIdToken"), eq(verifyOptions));

    Map<String, Object> params = new HashMap<>();
    params.put("state", "1234");
    params.put("id_token", "frontIdToken");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));

    RequestProcessor handler = new RequestProcessor(client, "id_token", verifyOptions, tokenVerifier, true);
    handler.process(request, response);
}
 
Example 12
Source File: GenerateServiceTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyServiceTicketFromCookie() throws Exception {
    final MockRequestContext context = new MockRequestContext();
    context.getFlowScope().put("service", TestUtils.getService());
    context.getFlowScope().put("ticketGrantingTicketId", this.ticketGrantingTicket.getId());
    final MockHttpServletRequest request = new MockHttpServletRequest();
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));
    request.addParameter("service", "service");
    request.setCookies(new Cookie("TGT", this.ticketGrantingTicket.getId()));

    this.action.execute(context);

    assertNotNull(WebUtils.getServiceTicketFromRequestScope(context));
}
 
Example 13
Source File: SendTicketGrantingTicketActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyTgtToSet() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");

    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(),
            request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    request.setCookies(response.getCookies());
    assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
 
Example 14
Source File: MockWebscriptServletRequest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
static public MockWebscriptServletRequest createMockWebscriptServletRequest(AbstractWebScript webScript,
		String method, String webscriptUrl, String controllerMapping, final Map<String, String> parameters,
		final Map<String, String> body, final Cookie[] cookies, final Map<String, Object> headers,
		final String contentType) throws IOException {
	Match match = new Match(null, ImmutableMap.of("", ""), webscriptUrl, webScript);
	MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method,
			"http://localhost/alfresco" + webscriptUrl + controllerMapping);
	mockHttpServletRequest.setServletPath("alfresco");
	mockHttpServletRequest.setContextPath("http://localhost/");
	mockHttpServletRequest.setContentType(contentType);
	if (parameters != null) {
		mockHttpServletRequest.setParameters(parameters);
	}
	if (cookies != null) {
		mockHttpServletRequest.setCookies(cookies);
	}
	if (headers != null && !headers.isEmpty()) {
		for (Entry<String, Object> headerEntry : headers.entrySet()) {
			mockHttpServletRequest.addHeader(headerEntry.getKey(), headerEntry.getValue());
		}
	}

	if (HttpMethod.POST.name().equals(method) && body != null) {
		mockHttpServletRequest.setContent(new ObjectMapper().writeValueAsString(body).getBytes());
	}

	MockWebscriptServletRequest webscriptServletRequest = new MockWebscriptServletRequest(mock(Runtime.class),
			mockHttpServletRequest, match);
	// if (content != null && !content.isEmpty()) {
	// Content mockedContent = mock(Content.class);
	// webscriptServletRequest.content = mockedContent;
	// }

	return webscriptServletRequest;
}
 
Example 15
Source File: AuthenticationServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenJwtInCookieAndHeader_whenGetJwtTokenFromRequest_thenPreferCookie() {
    String cookieName = authConfigurationProperties.getCookieProperties().getCookieName();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setCookies(new Cookie(cookieName, "jwt1"));
    request.addHeader(HttpHeaders.AUTHORIZATION, ApimlConstants.BEARER_AUTHENTICATION_PREFIX + " jwt2");
    Optional<String> token = authService.getJwtTokenFromRequest(request);
    assertTrue(token.isPresent());
    assertEquals("jwt1", token.get());
}
 
Example 16
Source File: RequestProcessorTest.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnProcessIfTokenRequestIsMissingAccessToken() throws Exception {
    exception.expect(InvalidRequestException.class);
    exception.expect(InvalidRequestExceptionMatcher.hasCode("a0.missing_access_token"));
    exception.expect(InvalidRequestExceptionMatcher.hasDescription("Access Token is missing from the response."));
    exception.expectMessage("Access Token is missing from the response.");

    Map<String, Object> params = new HashMap<>();
    params.put("state", "1234");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));

    RequestProcessor handler = new RequestProcessor(client, "token", verifyOptions);
    handler.process(request, response);
}
 
Example 17
Source File: ApiListenerServletTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
public void cookieNotFoundInCache401() throws ServletException, IOException, ListenerException, ConfigurationException {
	String uri = "cookie";
	addListener(uri, Methods.POST, AuthMethods.COOKIE);

	Map<String, String> headers = new HashMap<String, String>();
	MockHttpServletRequest request = createRequest(uri, Methods.POST, "{\"tralalalallala\":true}", headers);
	Cookie cookies = new Cookie("authenticationToken", "myToken");
	request.setCookies(cookies);
	Response result = service(request);

	assertEquals(401, result.getStatus());
	assertFalse(result.containsHeader("Allow"));
	assertNull(result.getErrorMessage());
}
 
Example 18
Source File: OAuth2AuthenticationServiceTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * If no refresh token is found and the access token has expired, then expect an exception.
 */
@Test
public void testRefreshGrantNoRefreshToken() {
    MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com");
    Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE);
    request.setCookies(accessTokenCookie);
    MockHttpServletResponse response = new MockHttpServletResponse();
    expectedException.expect(InvalidTokenException.class);
    refreshTokenFilter.refreshTokensIfExpiring(request, response);
}
 
Example 19
Source File: SendTicketGrantingTicketActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String TICKET_VALUE = "test";
    request.setCookies(new Cookie[] {new Cookie("TGT", "test5")});
    WebUtils.putTicketGrantingTicketInRequestScope(this.context, TICKET_VALUE);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    assertEquals(TICKET_VALUE, response.getCookies()[0].getValue());
}
 
Example 20
Source File: OAuth2AuthenticationServiceTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
public static MockHttpServletRequest createMockHttpServletRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest(HttpMethod.GET.name(), "http://www.test.com");
    Cookie accessTokenCookie = new Cookie(OAuth2CookieHelper.ACCESS_TOKEN_COOKIE, ACCESS_TOKEN_VALUE);
    Cookie refreshTokenCookie = new Cookie(OAuth2CookieHelper.REFRESH_TOKEN_COOKIE, REFRESH_TOKEN_VALUE);
    request.setCookies(accessTokenCookie, refreshTokenCookie);
    return request;
}