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

The following examples show how to use org.springframework.mock.web.mockhttpservletrequest#getSession() . 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: LogoutActionTest.java    From web-sso with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutWithCredentialButNoService() throws IOException {
	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	HttpSession session = request.getSession();
	CredentialResolver credentialResolver = Mockito.mock(CredentialResolver.class);
	logoutAction.setCredentialResolver(credentialResolver);
	Ki4soService ki4soService = Mockito.mock(Ki4soService.class);
	logoutAction.setKi4soService(ki4soService);
	
	//测试存在cookie,登出后要清除cookie值,但是service参数的值是null的情况。
	request.setCookies(new Cookie(WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY, "dddsd"));
	ModelAndView mv = logoutAction.logout(request, response,session);
	Assert.assertEquals(1, response.getCookies().length);
	Assert.assertEquals(0, response.getCookies()[0].getMaxAge());
	Assert.assertEquals("logoutSucess", mv.getViewName());
}
 
Example 2
Source File: HtmlUnitRequestBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void buildRequestSession() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession newSession = actualRequest.getSession();
	assertThat(newSession, notNullValue());
	assertSingleSessionCookie(
			"JSESSIONID=" + newSession.getId() + "; Path=/test; Domain=example.com");

	webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + newSession.getId());

	requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
	actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getSession(), sameInstance(newSession));
}
 
Example 3
Source File: HtmlUnitRequestBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void buildRequestSessionWithExistingSession() throws Exception {
	String sessionId = "session-id";
	webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession();
	assertThat(session.getId(), equalTo(sessionId));
	assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com");

	requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
	actualRequest = requestBuilder.buildRequest(servletContext);
	assertThat(actualRequest.getSession(), equalTo(session));

	webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW");
	actualRequest = requestBuilder.buildRequest(servletContext);
	assertThat(actualRequest.getSession(), not(equalTo(session)));
	assertSingleSessionCookie("JSESSIONID=" + actualRequest.getSession().getId()
			+ "; Path=/test; Domain=example.com");
}
 
Example 4
Source File: HtmlUnitRequestBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void buildRequestSessionInvalidate() throws Exception {
	String sessionId = "session-id";
	webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);

	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
	HttpSession sessionToRemove = actualRequest.getSession();
	sessionToRemove.invalidate();

	assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
	assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
			+ "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");

	webRequest.removeAdditionalHeader("Cookie");
	requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);

	actualRequest = requestBuilder.buildRequest(servletContext);

	assertThat(actualRequest.getSession().isNew(), equalTo(true));
	assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
}
 
Example 5
Source File: ManualLogoutIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@WithMockUser(value = "spring")
@Test
public void givenLoggedUserWhenUserLogoutThenSessionClearedAndAllCookiesCleared() throws Exception {

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE);

    Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE);
    randomCookie.setMaxAge(EXPIRY); // 10 minutes

    MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true).with(csrf()).session(session).cookie(randomCookie))
            .andExpect(status().is3xxRedirection())
            .andExpect(unauthenticated())
            .andExpect(cookie().maxAge(COOKIE_NAME, 0))
            .andReturn()
            .getRequest();

    HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession();
    assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME));
}
 
Example 6
Source File: LogoutActionTest.java    From web-sso with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutWithCredentialAndService() throws IOException {
	String servce  = "http://app.com/logoutSucess.do";
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setParameter(WebConstants.SERVICE_PARAM_NAME, servce);
	MockHttpServletResponse response = new MockHttpServletResponse();
	HttpSession session = request.getSession();
	CredentialResolver credentialResolver = Mockito.mock(CredentialResolver.class);
	logoutAction.setCredentialResolver(credentialResolver);
	Ki4soService ki4soService = Mockito.mock(Ki4soService.class);
	logoutAction.setKi4soService(ki4soService);
	
	//测试存在cookie,登出后要清除cookie值,但是service参数的值是null的情况。
	request.setCookies(new Cookie(WebConstants.KI4SO_SERVER_ENCRYPTED_CREDENTIAL_COOKIE_KEY, "dddsd"));
	
	ModelAndView mv = logoutAction.logout(request, response,session);
	Assert.assertEquals(1, response.getCookies().length);
	Assert.assertEquals(0, response.getCookies()[0].getMaxAge());
	RedirectView view = (RedirectView) mv.getView();
	Assert.assertEquals(servce, view.getUrl());
}
 
Example 7
Source File: HtmlUnitRequestBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void buildRequestSessionTrue() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession(true);
	assertThat(session, notNullValue());
}
 
Example 8
Source File: WebLookupTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSessionId() {
    final Log4jWebLifeCycle initializer = startInitializer();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();
    Log4jServletFilter.CURRENT_REQUEST.set(request);
    final WebLookup lookup = new WebLookup();
    assertNotNull(lookup.lookup(null, "session.id"));
    Log4jServletFilter.CURRENT_REQUEST.remove();
    assertNull(lookup.lookup(null, "session.id"));
    initializer.stop();
    ContextAnchor.THREAD_CONTEXT.remove();
}
 
Example 9
Source File: OAuth20AuthorizeControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.STATE, STATE);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<RegisteredService>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    assertEquals(
            OAuthUtils.addParameter(CAS_URL, "service", CAS_URL + CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL),
            redirectView.getUrl());
}
 
Example 10
Source File: OAuth20AuthorizeControllerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<RegisteredService>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    assertEquals(
            OAuthUtils.addParameter(CAS_URL, "service", CAS_URL + CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL),
            redirectView.getUrl());
}
 
Example 11
Source File: OAuth20AuthorizeControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.STATE, STATE);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    
    final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    reqSvc.setServerName(CAS_SERVER);
    reqSvc.setServerPort(CAS_PORT);
    reqSvc.setScheme(CAS_SCHEME);
    final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString()));
    final URL url2 = new URL(redirectView.getUrl());

    assertEquals(url, url2);
}
 
Example 12
Source File: OAuth20AuthorizeControllerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyOK() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT
            + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setLoginUrl(CAS_URL);
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    final HttpSession session = mockRequest.getSession();
    assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL));
    assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME));
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    
    final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    reqSvc.setServerName(CAS_SERVER);
    reqSvc.setServerPort(CAS_PORT);
    reqSvc.setScheme(CAS_SCHEME);
    final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString()));
    final URL url2 = new URL(redirectView.getUrl());

    assertEquals(url, url2);
}
 
Example 13
Source File: HttpSessionChallengeRepositoryTest.java    From webauthn4j-spring-security with Apache License 2.0 5 votes vote down vote up
@Test
public void saveChallenge_test() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    String attrName = ".test-challenge";

    target.setSessionAttributeName(attrName);
    Challenge challenge = target.generateChallenge();
    target.saveChallenge(challenge, request);

    HttpSession session = request.getSession();
    assertThat((Challenge) session.getAttribute(attrName)).isEqualTo(challenge);
}
 
Example 14
Source File: PrintingResultHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected final Map<String, Object> getSessionAttributes(MockHttpServletRequest request) {
	HttpSession session = request.getSession(false);
	if (session != null) {
		Enumeration<String> attrNames = session.getAttributeNames();
		if (attrNames != null) {
			return Collections.list(attrNames).stream().
					collect(Collectors.toMap(n -> n, session::getAttribute));
		}
	}
	return Collections.emptyMap();
}
 
Example 15
Source File: PrintingResultHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected final Map<String, Object> getSessionAttributes(MockHttpServletRequest request) {
	HttpSession session = request.getSession(false);
	if (session != null) {
		Enumeration<String> attrNames = session.getAttributeNames();
		if (attrNames != null) {
			return Collections.list(attrNames).stream().
					collect(Collectors.toMap(n -> n, session::getAttribute));
		}
	}
	return Collections.emptyMap();
}
 
Example 16
Source File: HtmlUnitRequestBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void buildRequestSessionFalseIsNull() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession(false);
	assertThat(session, nullValue());
}
 
Example 17
Source File: HtmlUnitRequestBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void buildRequestSessionFalseIsNull() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession(false);
	assertThat(session, nullValue());
}
 
Example 18
Source File: HtmlUnitRequestBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void buildRequestSessionTrue() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession(true);
	assertThat(session, notNullValue());
}
 
Example 19
Source File: HtmlUnitRequestBuilderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void buildRequestSessionTrue() throws Exception {
	MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

	HttpSession session = actualRequest.getSession(true);
	assertThat(session, notNullValue());
}
 
Example 20
Source File: ControllerTestDemo.java    From jeecg with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	MockHttpServletRequestBuilder requestBuilder = post("/");
	MockHttpServletRequest request = requestBuilder.buildRequest(this.wac.getServletContext());
	session = (MockHttpSession) request.getSession();
	this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
	this.testLogin(); //先调用登录
}