Search in sources :

Example 46 with MockHttpSession

use of org.springframework.mock.web.MockHttpSession in project hub-alert by blackducksoftware.

the class HomeControllerTestIT method testVerify.

@Test
@WithMockUser(roles = "ADMIN")
public void testVerify() throws Exception {
    final HttpHeaders headers = new HttpHeaders();
    final MockHttpSession session = new MockHttpSession();
    final ServletContext servletContext = webApplicationContext.getServletContext();
    final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get(homeVerifyUrl).with(SecurityMockMvcRequestPostProcessors.user("admin").roles("ADMIN"));
    request.session(session);
    final HttpServletRequest httpServletRequest = request.buildRequest(servletContext);
    final CsrfToken csrfToken = csrfTokenRepository.generateToken(httpServletRequest);
    csrfTokenRepository.saveToken(csrfToken, httpServletRequest, null);
    headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
    mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockHttpSession(org.springframework.mock.web.MockHttpSession) ServletContext(javax.servlet.ServletContext) CsrfToken(org.springframework.security.web.csrf.CsrfToken) WithMockUser(org.springframework.security.test.context.support.WithMockUser) ExternalConnectionTest(com.blackducksoftware.integration.test.annotation.ExternalConnectionTest) Test(org.junit.Test)

Example 47 with MockHttpSession

use of org.springframework.mock.web.MockHttpSession in project uplace.es by Uplace.

the class CustomAuditEventRepositoryIntTest method testAddEventWithWebAuthenticationDetails.

@Test
public void testAddEventWithWebAuthenticationDetails() {
    HttpSession session = new MockHttpSession(null, "test-session-id");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);
    request.setRemoteAddr("1.2.3.4");
    WebAuthenticationDetails details = new WebAuthenticationDetails(request);
    Map<String, Object> data = new HashMap<>();
    data.put("test-key", details);
    AuditEvent event = new AuditEvent("test-user", "test-type", data);
    customAuditEventRepository.add(event);
    List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
    assertThat(persistentAuditEvents).hasSize(1);
    PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
    assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
    assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
Also used : PersistentAuditEvent(com.arnaugarcia.uplace.domain.PersistentAuditEvent) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) MockHttpSession(org.springframework.mock.web.MockHttpSession) AuditEvent(org.springframework.boot.actuate.audit.AuditEvent) PersistentAuditEvent(com.arnaugarcia.uplace.domain.PersistentAuditEvent) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 48 with MockHttpSession

use of org.springframework.mock.web.MockHttpSession in project cas by apereo.

the class OAuth20AccessTokenControllerTests method ensureOnlyRefreshTokenIsAcceptedForRefreshGrant.

@Test
public void ensureOnlyRefreshTokenIsAcceptedForRefreshGrant() throws Exception {
    addRegisteredService(true);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    final MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    String response = mockResponse.getContentAsString();
    final String refreshToken = Arrays.stream(response.split("&")).filter(f -> f.startsWith(OAuth20Constants.REFRESH_TOKEN)).map(f -> StringUtils.remove(f, OAuth20Constants.REFRESH_TOKEN + "=")).findFirst().get();
    final String accessToken = Arrays.stream(response.split("&")).filter(f -> f.startsWith(OAuth20Constants.ACCESS_TOKEN)).map(f -> StringUtils.remove(f, OAuth20Constants.ACCESS_TOKEN + "=")).findFirst().get();
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuth20Constants.REFRESH_TOKEN, accessToken);
    mockResponse = new MockHttpServletResponse();
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    mockRequest.setParameter(OAuth20Constants.REFRESH_TOKEN, refreshToken);
    mockResponse = new MockHttpServletResponse();
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    response = mockResponse.getContentAsString();
    assertTrue(response.contains(OAuth20Constants.ACCESS_TOKEN));
}
Also used : Arrays(java.util.Arrays) HttpStatus(org.apache.http.HttpStatus) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) AlwaysExpiresExpirationPolicy(org.apereo.cas.ticket.support.AlwaysExpiresExpirationPolicy) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ArrayList(java.util.ArrayList) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) Before(org.junit.Before) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) OAuth20AccessTokenEndpointController(org.apereo.cas.support.oauth.web.endpoints.OAuth20AccessTokenEndpointController) DefaultRefreshTokenFactory(org.apereo.cas.ticket.refreshtoken.DefaultRefreshTokenFactory) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) DefaultOAuthCodeFactory(org.apereo.cas.ticket.code.DefaultOAuthCodeFactory) Service(org.apereo.cas.authentication.principal.Service) Principal(org.apereo.cas.authentication.principal.Principal) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) Assert(org.junit.Assert) CoreAuthenticationTestUtils(org.apereo.cas.authentication.CoreAuthenticationTestUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 49 with MockHttpSession

use of org.springframework.mock.web.MockHttpSession in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyTokenRedirectToClientWithState.

@Test
public void verifyTokenRedirectToClientWithState() throws Exception {
    clearAllServices();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    mockRequest.setParameter(OAuth20Constants.STATE, STATE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    this.servicesManager.save(service);
    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);
    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));
    assertTrue(redirectUrl.contains('&' + OAuth20Constants.STATE + '=' + STATE));
    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) this.ticketRegistry.getTicket(code);
    assertNotNull(accessToken);
    final Principal principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
Also used : CasProfile(org.pac4j.cas.profile.CasProfile) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) RedirectView(org.springframework.web.servlet.view.RedirectView) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Principal(org.apereo.cas.authentication.principal.Principal) Test(org.junit.Test)

Example 50 with MockHttpSession

use of org.springframework.mock.web.MockHttpSession in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyRedirectToApproval.

@Test
public void verifyRedirectToApproval() throws Exception {
    clearAllServices();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.CODE.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(false);
    this.servicesManager.save(service);
    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);
    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuth20Constants.CONFIRM_VIEW, modelAndView.getViewName());
    final Map<String, Object> model = modelAndView.getModel();
    assertEquals(AUTHORIZE_URL, model.get("callbackUrl"));
    assertEquals(SERVICE_NAME, model.get("serviceName"));
}
Also used : CasProfile(org.pac4j.cas.profile.CasProfile) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Aggregations

MockHttpSession (org.springframework.mock.web.MockHttpSession)106 Test (org.junit.Test)84 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)44 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)34 DhisWebSpringTest (org.hisp.dhis.webapi.DhisWebSpringTest)23 HashMap (java.util.HashMap)13 AbstractWebApiTest (org.hisp.dhis.webapi.documentation.controller.AbstractWebApiTest)13 MockFilterChain (org.springframework.mock.web.MockFilterChain)12 FieldDescriptor (org.springframework.restdocs.payload.FieldDescriptor)11 ModelAndView (org.springframework.web.servlet.ModelAndView)11 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)9 FilterChain (javax.servlet.FilterChain)8 MockServletContext (org.springframework.mock.web.MockServletContext)8 SessionRegistry (org.springframework.security.core.session.SessionRegistry)8 ConcurrentSessionFilter (org.springframework.security.web.session.ConcurrentSessionFilter)8 Principal (org.apereo.cas.authentication.principal.Principal)7 DataElement (org.hisp.dhis.dataelement.DataElement)7 CasProfile (org.pac4j.cas.profile.CasProfile)7 InputStream (java.io.InputStream)6 Before (org.junit.Before)6