org.springframework.mock.web.MockHttpServletRequest

Here are the examples of the java api class org.springframework.mock.web.MockHttpServletRequest taken from open source projects.

1. TestAddCobar#testAddCobar()

Project: cobar
Source File: TestAddCobar.java
View license
public void testAddCobar() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    UserDO user = new UserDO();
    user.setStatus(ConstantDefine.NORMAL);
    user.setUser_role(ConstantDefine.CLUSTER_ADMIN);
    session.setAttribute("user", user);
    request.setSession(session);
    request.addParameter("clusterId", "1");
    request.addParameter("host", "1.2.4.3");
    request.addParameter("cobarName", "test");
    request.addParameter("port", "8066");
    request.addParameter("userName", "test");
    request.addParameter("password", "TTT");
    request.addParameter("status", "ACTIVE");
    ModelAndView mav = addcobar.handleRequest(request, new MockHttpServletResponse());
    Assert.assertEquals("add cobar success", String.valueOf(mav.getModel().get("info")));
}

2. BaseUriDetectionTest#testDetection()

Project: wink
Source File: BaseUriDetectionTest.java
View license
// class GetBaseUriResource
public void testDetection() throws Exception {
    MockHttpServletRequest request = MockRequestConstructor.constructMockRequest("GET", "/context/baseUri", "*/*");
    request.setScheme("http");
    request.setServerName("myServer");
    request.setContextPath("/context");
    request.setServerPort(9090);
    MockHttpServletResponse response = invoke(request);
    String content = response.getContentAsString();
    assertEquals("base URI in content", "http://myServer:9090/context/", content);
    request = MockRequestConstructor.constructMockRequest("GET", "/con%20text/baseUri", "*/*");
    request.setScheme("https");
    request.setServerName("backupSrv");
    request.setContextPath("/con%20text");
    request.setServerPort(2);
    MockHttpServletResponse response2 = invoke(request);
    String content2 = response2.getContentAsString();
    assertEquals("escaped base URI in content", "https://backupSrv:2/con%20text/", content2);
}

3. HttpHeadersImplTest#testHttpHeaderContext()

Project: wink
Source File: HttpHeadersImplTest.java
View license
@Test
public void testHttpHeaderContext() throws Exception {
    MockHttpServletRequest servletRequest = MockRequestConstructor.constructMockRequest("GET", "/test", "application/xml;q=0.3, text/plain, text/html;q=0.5");
    servletRequest.addHeader("Content-Type", "application/xml");
    servletRequest.addHeader("Content-Language", "en-us, he");
    servletRequest.addHeader("Cookie", "$Version=1; cookie1_name=cookie1_val");
    servletRequest.addHeader("Cookie", "$Version=1; cookie2_name=cookie2_val");
    servletRequest.addHeader("Accept-Language", "en;q=0.3, en-us, he;q=0.5");
    servletRequest.addHeader("header1", "value1");
    servletRequest.addHeader("header1", "value2");
    servletRequest.addHeader("header2", "value2");
    invoke(servletRequest);
}

4. OAuth20AuthorizeControllerTests#verifyCodeNoProfile()

View license
@Test
public void verifyCodeNoProfile() throws Exception {
    clearAllServices();
    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.RESPONSE_TYPE, OAuthResponseType.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(true);
    oAuth20AuthorizeController.getServicesManager().save(service);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    final ModelAndView modelAndView = oAuth20AuthorizeController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(OAuthConstants.ERROR_VIEW, modelAndView.getViewName());
}

5. OAuth20AuthorizeControllerTests#verifyCodeNoProfile()

View license
@Test
public void verifyCodeNoProfile() throws Exception {
    clearAllServices();
    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.RESPONSE_TYPE, OAuthResponseType.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(true);
    oAuth20AuthorizeController.getServicesManager().save(service);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    final ModelAndView modelAndView = oAuth20AuthorizeController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(OAuthConstants.ERROR_VIEW, modelAndView.getViewName());
}

6. InsecureChannelProcessorTests#testDecideDetectsUnacceptableChannel()

View license
@Test
public void testDecideDetectsUnacceptableChannel() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("info=true");
    request.setServerName("localhost");
    request.setContextPath("/bigapp");
    request.setServletPath("/servlet");
    request.setScheme("https");
    request.setSecure(true);
    request.setServerPort(8443);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    InsecureChannelProcessor processor = new InsecureChannelProcessor();
    processor.decide(fi, SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL" }));
    assertThat(fi.getResponse().isCommitted()).isTrue();
}

7. SecureChannelProcessorTests#testDecideDetectsAcceptableChannel()

View license
// ~ Methods
// ========================================================================================================
@Test
public void testDecideDetectsAcceptableChannel() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("info=true");
    request.setServerName("localhost");
    request.setContextPath("/bigapp");
    request.setServletPath("/servlet");
    request.setScheme("https");
    request.setSecure(true);
    request.setServerPort(8443);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    SecureChannelProcessor processor = new SecureChannelProcessor();
    processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL"));
    assertThat(fi.getResponse().isCommitted()).isFalse();
}

8. LoginUrlAuthenticationEntryPointTests#testServerSideRedirectWithoutForceHttpsForwardsToLoginPage()

View license
@Test
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage() throws Exception {
    LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
    ep.setUseForward(true);
    ep.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/bigWebApp/some_path");
    request.setServletPath("/some_path");
    request.setContextPath("/bigWebApp");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setContextPath("/bigWebApp");
    request.setServerPort(80);
    MockHttpServletResponse response = new MockHttpServletResponse();
    ep.commence(request, response, null);
    assertThat(response.getForwardedUrl()).isEqualTo("/hello");
}

9. LoginUrlAuthenticationEntryPointTests#testServerSideRedirectWithForceHttpsRedirectsCurrentRequest()

View license
@Test
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest() throws Exception {
    LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
    ep.setUseForward(true);
    ep.setForceHttps(true);
    ep.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/bigWebApp/some_path");
    request.setServletPath("/some_path");
    request.setContextPath("/bigWebApp");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setContextPath("/bigWebApp");
    request.setServerPort(80);
    MockHttpServletResponse response = new MockHttpServletResponse();
    ep.commence(request, response, null);
    assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/some_path");
}

10. FilterInvocationTests#testGettersAndStringMethods()

View license
// ~ Methods
// ========================================================================================================
@Test
public void testGettersAndStringMethods() {
    MockHttpServletRequest request = new MockHttpServletRequest(null, null);
    request.setServletPath("/HelloWorld");
    request.setPathInfo("/some/more/segments.html");
    request.setServerName("www.example.com");
    request.setScheme("http");
    request.setServerPort(80);
    request.setContextPath("/mycontext");
    request.setRequestURI("/mycontext/HelloWorld/some/more/segments.html");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain chain = mock(FilterChain.class);
    FilterInvocation fi = new FilterInvocation(request, response, chain);
    assertThat(fi.getRequest()).isEqualTo(request);
    assertThat(fi.getHttpRequest()).isEqualTo(request);
    assertThat(fi.getResponse()).isEqualTo(response);
    assertThat(fi.getHttpResponse()).isEqualTo(response);
    assertThat(fi.getChain()).isEqualTo(chain);
    assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld/some/more/segments.html");
    assertThat(fi.toString()).isEqualTo("FilterInvocation: URL: /HelloWorld/some/more/segments.html");
    assertThat(fi.getFullRequestUrl()).isEqualTo("http://www.example.com/mycontext/HelloWorld/some/more/segments.html");
}

11. FilterInvocationTests#testStringMethodsWithAQueryString()

View license
@Test
public void testStringMethodsWithAQueryString() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("foo=bar");
    request.setServletPath("/HelloWorld");
    request.setServerName("www.example.com");
    request.setScheme("http");
    request.setServerPort(80);
    request.setContextPath("/mycontext");
    request.setRequestURI("/mycontext/HelloWorld");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld?foo=bar");
    assertThat(fi.toString()).isEqualTo("FilterInvocation: URL: /HelloWorld?foo=bar");
    assertThat(fi.getFullRequestUrl()).isEqualTo("http://www.example.com/mycontext/HelloWorld?foo=bar");
}

12. OpenIdServiceTests#verifyEquals()

Project: cas
Source File: OpenIdServiceTests.java
View license
@Test
public void verifyEquals() {
    final MockHttpServletRequest request1 = new MockHttpServletRequest();
    request1.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request1.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    request1.addParameter("openid.mode", "openid.checkid_setup");
    final MockHttpServletRequest request2 = new MockHttpServletRequest();
    request2.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request2.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    final OpenIdService o1 = openIdServiceFactory.createService(request);
    final OpenIdService o2 = openIdServiceFactory.createService(request);
    assertTrue(o1.equals(o2));
    assertFalse(o1.equals(new Object()));
}

13. OpenIdServiceTests#verifyEquals()

Project: passport
Source File: OpenIdServiceTests.java
View license
@Test
public void verifyEquals() {
    final MockHttpServletRequest request1 = new MockHttpServletRequest();
    request1.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request1.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    request1.addParameter("openid.mode", "openid.checkid_setup");
    final MockHttpServletRequest request2 = new MockHttpServletRequest();
    request2.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request2.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    final OpenIdService o1 = OpenIdService.createServiceFrom(request1, null);
    final OpenIdService o2 = OpenIdService.createServiceFrom(request2, null);
    assertTrue(o1.equals(o2));
    assertFalse(o1.equals(new Object()));
}

14. OpenIdServiceTests#verifyEquals()

Project: passport
Source File: OpenIdServiceTests.java
View license
@Test
public void verifyEquals() {
    final MockHttpServletRequest request1 = new MockHttpServletRequest();
    request1.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request1.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    request1.addParameter("openid.mode", "openid.checkid_setup");
    final MockHttpServletRequest request2 = new MockHttpServletRequest();
    request2.addParameter("openid.identity", "http://openid.ja-sig.org/battags");
    request2.addParameter("openid.return_to", "http://www.ja-sig.org/?service=fa");
    final OpenIdService o1 = openIdServiceFactory.createService(request);
    final OpenIdService o2 = openIdServiceFactory.createService(request);
    assertTrue(o1.equals(o2));
    assertFalse(o1.equals(new Object()));
}

15. RedPenResourceTest#constructMockRequest()

Project: redpen
Source File: RedPenResourceTest.java
View license
private MockHttpServletRequest constructMockRequest(String method, String requestURI, String acceptHeader, String contentType) {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest() {

        public String getPathTranslated() {
            // prevent Spring to resolve the file on the filesystem which fails
            return null;
        }

        @Override
        public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException {
            return null;
        }
    };
    mockRequest.setMethod(method);
    mockRequest.setRequestURI(requestURI);
    mockRequest.setServerPort(8080);
    mockRequest.addHeader("Accept", acceptHeader);
    mockRequest.addHeader("Content-Type", contentType);
    mockRequest.setContentType(contentType);
    return mockRequest;
}

16. SessionManagementConfigurerServlet31Tests#changeSessionIdDefaultsInServlet31Plus()

View license
@Test
public void changeSessionIdDefaultsInServlet31Plus() throws Exception {
    spy(ReflectionUtils.class);
    Method method = mock(Method.class);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();
    request.setServletPath("/login");
    request.setMethod("POST");
    request.setParameter("username", "user");
    request.setParameter("password", "password");
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    CsrfToken token = repository.generateToken(request);
    repository.saveToken(token, request, response);
    request.setParameter(token.getParameterName(), token.getToken());
    when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
    loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
    springSecurityFilterChain.doFilter(request, response, chain);
    verifyStatic();
    ReflectionUtils.invokeMethod(same(method), any(HttpServletRequest.class));
}

17. HttpPathParameterStrippingTests#adminFilePatternCannotBeBypassedByAddingPathParameters()

View license
@Test
public void adminFilePatternCannotBeBypassedByAddingPathParameters() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setServletPath("/secured/admin.html;x=user.html");
    request.setSession(createAuthenticatedSession("ROLE_USER"));
    MockHttpServletResponse response = new MockHttpServletResponse();
    fcp.doFilter(request, response, new MockFilterChain());
    assertThat(response.getStatus()).isEqualTo(403);
    // Try with pathInfo
    request = new MockHttpServletRequest();
    request.setServletPath("/secured");
    request.setPathInfo("/admin.html;x=user.html");
    request.setSession(createAuthenticatedSession("ROLE_USER"));
    response = new MockHttpServletResponse();
    fcp.doFilter(request, response, new MockFilterChain());
    assertThat(response.getStatus()).isEqualTo(403);
}

18. InsecureChannelProcessorTests#testDecideDetectsAcceptableChannel()

View license
@Test
public void testDecideDetectsAcceptableChannel() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("info=true");
    request.setServerName("localhost");
    request.setContextPath("/bigapp");
    request.setServletPath("/servlet");
    request.setScheme("http");
    request.setServerPort(8080);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    InsecureChannelProcessor processor = new InsecureChannelProcessor();
    processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL"));
    assertThat(fi.getResponse().isCommitted()).isFalse();
}

19. SecureChannelProcessorTests#testDecideDetectsUnacceptableChannel()

View license
@Test
public void testDecideDetectsUnacceptableChannel() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("info=true");
    request.setServerName("localhost");
    request.setContextPath("/bigapp");
    request.setServletPath("/servlet");
    request.setScheme("http");
    request.setServerPort(8080);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    SecureChannelProcessor processor = new SecureChannelProcessor();
    processor.decide(fi, SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL" }));
    assertThat(fi.getResponse().isCommitted()).isTrue();
}

20. ExceptionTranslationFilterTests#redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException()

View license
@Test
public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setServletPath("/secure/page.html");
    request.setServerPort(80);
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setContextPath("/mycontext");
    request.setRequestURI("/mycontext/secure/page.html");
    // Setup the FilterChain to thrown an authentication failure exception
    FilterChain fc = mock(FilterChain.class);
    doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
    // Test
    ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
    filter.afterPropertiesSet();
    MockHttpServletResponse response = new MockHttpServletResponse();
    filter.doFilter(request, response, fc);
    assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp");
    assertThat(getSavedRequestUrl(request)).isEqualTo("http://www.example.com/mycontext/secure/page.html");
}

21. LoginUrlAuthenticationEntryPointTests#testNormalOperation()

View license
@Test
public void testNormalOperation() throws Exception {
    LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
    ep.setPortMapper(new PortMapperImpl());
    ep.setPortResolver(new MockPortResolver(80, 443));
    ep.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/some_path");
    request.setContextPath("/bigWebApp");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setContextPath("/bigWebApp");
    request.setServerPort(80);
    MockHttpServletResponse response = new MockHttpServletResponse();
    ep.commence(request, response, null);
    assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello");
}

22. LoginUrlAuthenticationEntryPointTests#testOperationWhenHttpsRequestsButHttpsPortUnknown()

View license
@Test
public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception {
    LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
    ep.setPortResolver(new MockPortResolver(8888, 1234));
    ep.setForceHttps(true);
    ep.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/some_path");
    request.setContextPath("/bigWebApp");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setContextPath("/bigWebApp");
    // NB: Port we can't resolve
    request.setServerPort(8888);
    MockHttpServletResponse response = new MockHttpServletResponse();
    ep.commence(request, response, null);
    // Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port
    // mapping
    assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com:8888/bigWebApp/hello");
}

23. DebugFilterTest#doFilterLogsProperly()

View license
@Test
public void doFilterLogsProperly() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setServletPath("/path");
    request.setPathInfo("/");
    request.addHeader("A", "A Value");
    request.addHeader("A", "Another Value");
    request.addHeader("B", "B Value");
    filter.doFilter(request, response, filterChain);
    verify(logger).info(logCaptor.capture());
    assertThat(logCaptor.getValue()).isEqualTo("Request received for GET '/path/':\n" + "\n" + request + "\n" + "\n" + "servletPath:/path\n" + "pathInfo:/\n" + "headers: \n" + "A: A Value, Another Value\n" + "B: B Value\n" + "\n" + "\n" + "Security filter chain: no match");
}

24. FilterInvocationTests#testStringMethodsWithoutAnyQueryString()

View license
@Test
public void testStringMethodsWithoutAnyQueryString() {
    MockHttpServletRequest request = new MockHttpServletRequest(null, null);
    request.setServletPath("/HelloWorld");
    request.setServerName("www.example.com");
    request.setScheme("http");
    request.setServerPort(80);
    request.setContextPath("/mycontext");
    request.setRequestURI("/mycontext/HelloWorld");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
    assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld");
    assertThat(fi.toString()).isEqualTo("FilterInvocation: URL: /HelloWorld");
    assertThat(fi.getFullRequestUrl()).isEqualTo("http://www.example.com/mycontext/HelloWorld");
}

25. AuthorizationServerFilterTest#testCorsHeadersPreflight()

View license
@Test
public void testCorsHeadersPreflight() throws IOException, ServletException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(HttpHeaders.AUTHORIZATION, "bearer dummy-access-token");
    request.addHeader("Origin", "http://www.test.org");
    request.addHeader("Access-Control-Request-Method", "PATCH");
    request.addHeader("Access-Control-Request-Headers", HttpHeaders.AUTHORIZATION + ", X-Custom-Header");
    request.setMethod("OPTIONS");
    MockHttpServletResponse response = new MockHttpServletResponse();
    //null FilterChain as chain.filter to proceed the flow is not called with preflight
    filter.doFilter(request, response, null);
    assertEquals("86400", response.getHeader("Access-Control-Max-Age"));
    assertEquals(HttpHeaders.AUTHORIZATION + ", X-Custom-Header", response.getHeader("Access-Control-Allow-Headers"));
    assertEquals("GET, OPTIONS, HEAD, PUT, PATCH, POST, DELETE", response.getHeader("Access-Control-Allow-Methods"));
    assertEquals("*", response.getHeader("Access-Control-Allow-Origin"));
}

26. OAuth20AccessTokenControllerTests#verifyClientBadAuthorizationCode()

View license
@Test
public void verifyClientBadAuthorizationCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, "badValue");
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

27. OAuth20AccessTokenControllerTests#verifyClientNoCasService()

View license
@Test
public void verifyClientNoCasService() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService registeredService = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);
    final OAuthCode code = addCode(principal, registeredService);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

28. OAuth20AccessTokenControllerTests#verifyClientRedirectUriDoesNotStartWithServiceId()

View license
@Test
public void verifyClientRedirectUriDoesNotStartWithServiceId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, OTHER_REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

29. OAuth20AccessTokenControllerTests#verifyClientWrongSecret()

View license
@Test
public void verifyClientWrongSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

30. FreemarkerServletTest#createMockHttpServletRequest()

View license
private MockHttpServletRequest createMockHttpServletRequest(final ServletContext servletContext, final String pathInfo, final Locale requestLocale) {
    MockHttpServletRequest servletRequest = new MockHttpServletRequest(servletContext) {

        @Override
        public Locale getLocale() {
            return requestLocale;
        }
    };
    servletRequest.setServerName("localhost");
    servletRequest.setServerPort(8080);
    servletRequest.setContextPath("");
    servletRequest.setRequestURI(pathInfo);
    servletRequest.setPathInfo(pathInfo);
    return servletRequest;
}

31. AuthenticationViaFormActionTests#verifySuccessfulAuthenticationWithServiceAndWarn()

View license
@Test
public void verifySuccessfulAuthenticationWithServiceAndWarn() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");
    request.addParameter("service", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);
    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}

32. AuthenticationViaFormActionTests#verifyRenewWithServiceAndSameCredentials()

View license
@Test
public void verifyRenewWithServiceAndSameCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
    context.getFlowScope().put("service", TestUtils.getService());
    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("warn", this.action.submit(context, c, messageContext).getId());
}

33. AuthenticationViaFormActionTests#verifyRenewWithServiceAndDifferentCredentials()

View license
@Test
public void verifyRenewWithServiceAndDifferentCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");
    request.addParameter("username", "test2");
    request.addParameter("password", "test2");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
}

34. OAuth20AccessTokenControllerTests#verifyClientBadAuthorizationCode()

View license
@Test
public void verifyClientBadAuthorizationCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, "badValue");
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

35. OAuth20AccessTokenControllerTests#verifyClientNoCasService()

View license
@Test
public void verifyClientNoCasService() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService registeredService = getRegisteredService(REDIRECT_URI, CLIENT_SECRET);
    final OAuthCode code = addCode(principal, registeredService);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

36. OAuth20AccessTokenControllerTests#verifyClientRedirectUriDoesNotStartWithServiceId()

View license
@Test
public void verifyClientRedirectUriDoesNotStartWithServiceId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, OTHER_REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

37. OAuth20AccessTokenControllerTests#verifyClientWrongSecret()

View license
@Test
public void verifyClientWrongSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

38. SessionManagementConfigServlet31Tests#changeSessionIdDefaultsInServlet31Plus()

View license
@Test
public void changeSessionIdDefaultsInServlet31Plus() throws Exception {
    spy(ReflectionUtils.class);
    Method method = mock(Method.class);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();
    request.setServletPath("/login");
    request.setMethod("POST");
    request.setParameter("username", "user");
    request.setParameter("password", "password");
    when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
    loadContext("<http>\n" + "        <form-login/>\n" + "        <session-management/>\n" + "        <csrf disabled='true'/>\n" + "    </http>" + XML_AUTHENTICATION_MANAGER);
    springSecurityFilterChain.doFilter(request, response, chain);
    verifyStatic();
    ReflectionUtils.invokeMethod(same(method), any(HttpServletRequest.class));
}

39. SessionManagementConfigServlet31Tests#changeSessionId()

View license
@Test
public void changeSessionId() throws Exception {
    spy(ReflectionUtils.class);
    Method method = mock(Method.class);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();
    request.setServletPath("/login");
    request.setMethod("POST");
    request.setParameter("username", "user");
    request.setParameter("password", "password");
    when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
    loadContext("<http>\n" + "        <form-login/>\n" + "        <session-management session-fixation-protection='changeSessionId'/>\n" + "        <csrf disabled='true'/>\n" + "    </http>" + XML_AUTHENTICATION_MANAGER);
    springSecurityFilterChain.doFilter(request, response, chain);
    verifyStatic();
    ReflectionUtils.invokeMethod(same(method), any(HttpServletRequest.class));
}

40. DefaultFilterInvocationSecurityMetadataSourceTests#createFilterInvocation()

View license
private FilterInvocation createFilterInvocation(String servletPath, String pathInfo, String queryString, String method) {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(null);
    request.setMethod(method);
    request.setServletPath(servletPath);
    request.setPathInfo(pathInfo);
    request.setQueryString(queryString);
    return new FilterInvocation(request, new MockHttpServletResponse(), mock(FilterChain.class));
}

41. ConnectSupportTest#completeConnection_OAuth2()

View license
@Test
public void completeConnection_OAuth2() {
    ConnectSupport support = new ConnectSupport();
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.addParameter("code", "authorization-grant");
    mockRequest.addParameter("state", "STATE");
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setRequestURI("/connect/someprovider");
    mockRequest.getSession().setAttribute("oauth2State", "STATE");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    Connection<?> connection = support.completeConnection(new TestOAuth2ConnectionFactory(), request);
    assertEquals("TestUser", connection.getDisplayName());
    assertEquals("http://someprovider.com/images/testuser.jpg", connection.getImageUrl());
    assertEquals("http://someprovider.com/testuser", connection.getProfileUrl());
}

42. ServletFilterTest#testServletFilter()

Project: wink
Source File: ServletFilterTest.java
View license
@Test
public void testServletFilter() throws Exception {
    MockHttpServletRequest servletRequest = MockRequestConstructor.constructMockRequest("POST", "/test", MediaType.TEXT_PLAIN);
    servletRequest.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    servletRequest.setContent("formParam=single&formParamMulti=one&formParamMulti=two".getBytes());
    servletRequest.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    servletRequest.setParameter("formParam", "single");
    servletRequest.setParameter("formParamMulti", new String[] { "one", "two" });
    // Perform servletFilter.doFilter just before HttpServlet.service is
    // called in invoke.
    // Honestly, having a real servlet filter here is overkill. We could
    // have just as simply NOT
    // set any content on the servletRequest object to simulate consumption
    // of the request message body.
    // In the interest of brevity, however, let's do it the right way.
    Filter servletFilter = new MyServletFilter();
    servletFilter.doFilter(servletRequest, null, null);
    MockHttpServletResponse servletResponse = invoke(servletRequest);
    assertEquals("single_two_response", servletResponse.getContentAsString());
}

43. RssFeedServletTest#testRequestNewArtifactsInRepo()

Project: archiva
Source File: RssFeedServletTest.java
View license
@Test
public void testRequestNewArtifactsInRepo() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/feeds/test-repo");
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod("GET");
    Base64 encoder = new Base64(0, new byte[0]);
    String userPass = "user1:password1";
    String encodedUserPass = encoder.encodeToString(userPass.getBytes());
    request.addHeader("Authorization", "BASIC " + encodedUserPass);
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    rssFeedServlet.doGet(request, mockHttpServletResponse);
    assertEquals(RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader("CONTENT-TYPE"));
    assertNotNull("Should have recieved a response", mockHttpServletResponse.getContentAsString());
    assertEquals("Should have been an OK response code.", HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());
}

44. RssFeedServletTest#testRequestNewVersionsOfArtifact()

Project: archiva
Source File: RssFeedServletTest.java
View license
@Test
public void testRequestNewVersionsOfArtifact() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/feeds/org/apache/archiva/artifact-two");
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod("GET");
    //WebRequest request = new GetMethodWebRequest( "http://localhost/feeds/org/apache/archiva/artifact-two" );
    Base64 encoder = new Base64(0, new byte[0]);
    String userPass = "user1:password1";
    String encodedUserPass = encoder.encodeToString(userPass.getBytes());
    request.addHeader("Authorization", "BASIC " + encodedUserPass);
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    rssFeedServlet.doGet(request, mockHttpServletResponse);
    assertEquals(RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader("CONTENT-TYPE"));
    assertNotNull("Should have recieved a response", mockHttpServletResponse.getContentAsString());
    assertEquals("Should have been an OK response code.", HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());
}

45. RssFeedServletTest#testInvalidAuthenticationRequest()

Project: archiva
Source File: RssFeedServletTest.java
View license
@Test
public void testInvalidAuthenticationRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/feeds/unauthorized-repo");
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod("GET");
    Encoder encoder = new Base64();
    String userPass = "unauthUser:unauthPass";
    String encodedUserPass = new String((byte[]) encoder.encode(userPass.getBytes()));
    request.addHeader("Authorization", "BASIC " + encodedUserPass);
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    rssFeedServlet.doGet(request, mockHttpServletResponse);
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus());
}

46. RssFeedServletTest#testUnauthorizedRequest()

Project: archiva
Source File: RssFeedServletTest.java
View license
@Test
public void testUnauthorizedRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/feeds/unauthorized-repo");
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod("GET");
    Base64 encoder = new Base64(0, new byte[0]);
    String userPass = "user1:password1";
    String encodedUserPass = encoder.encodeToString(userPass.getBytes());
    request.addHeader("Authorization", "BASIC " + encodedUserPass);
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    rssFeedServlet.doGet(request, mockHttpServletResponse);
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus());
}

47. AuthenticationViaFormActionTests#verifySuccessfulAuthenticationWithServiceAndWarn()

View license
@Test
public void verifySuccessfulAuthenticationWithServiceAndWarn() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");
    request.addParameter("service", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    final Credential c = org.apereo.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);
    assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, this.action.doExecute(context).getId());
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}

48. AuthenticationViaFormActionTests#verifyRenewWithServiceAndSameCredentials()

View license
@Test
public void verifyRenewWithServiceAndSameCredentials() throws Exception {
    final Credential c = org.apereo.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Service service = TestUtils.getService(TestUtils.CONST_TEST_URL);
    final AuthenticationResult ctx = org.apereo.cas.authentication.TestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), service, c);
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", TestUtils.getService(TestUtils.CONST_TEST_URL).getId());
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
    context.getFlowScope().put("service", TestUtils.getService());
    assertEquals(CasWebflowConstants.TRANSITION_ID_WARN, this.action.doExecute(context).getId());
}

49. OAuth20AccessTokenControllerTests#verifyClientNoClientId()

View license
//
//
// authorization code grant type tests
//
//
@Test
public void verifyClientNoClientId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

50. OAuth20AccessTokenControllerTests#verifyClientNoRedirectUri()

View license
@Test
public void verifyClientNoRedirectUri() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

51. OAuth20AccessTokenControllerTests#verifyClientNoAuthorizationCode()

View license
@Test
public void verifyClientNoAuthorizationCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

52. OAuth20AccessTokenControllerTests#verifyClientNoClientSecret()

View license
@Test
public void verifyClientNoClientSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

53. OAuth20AccessTokenControllerTests#verifyClientNoCode()

View license
@Test
public void verifyClientNoCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    addCode(principal, service);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

54. OAuth20AccessTokenControllerTests#verifyUserNoCasService()

View license
@Test
public void verifyUserNoCasService() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

55. OAuth20AccessTokenControllerTests#verifyUserBadAuthorizationCode()

View license
@Test
public void verifyUserBadAuthorizationCode() throws Exception {
    addRegisteredService();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

56. OAuth20AccessTokenControllerTests#verifyUserBadCredentials()

View license
@Test
public void verifyUserBadCredentials() throws Exception {
    addRegisteredService();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, "badPassword");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

57. OAuth20AccessTokenControllerTests#verifyRefreshTokenExpiredToken()

View license
//
//
// refresh token grant type tests
//
//
@Test
public void verifyRefreshTokenExpiredToken() throws Exception {
    final Principal principal = createPrincipal();
    final RegisteredService registeredService = addRegisteredService();
    final Authentication authentication = getAuthentication(principal);
    final Service service = new OAuthWebApplicationService(registeredService);
    final DefaultRefreshTokenFactory expiringRefreshTokenFactory = new DefaultRefreshTokenFactory();
    expiringRefreshTokenFactory.setExpirationPolicy(new AlwaysExpiresExpirationPolicy());
    final RefreshToken refreshToken = expiringRefreshTokenFactory.create(service, authentication);
    oAuth20AccessTokenController.getTicketRegistry().addTicket(refreshToken);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_GRANT, mockResponse.getContentAsString());
}

58. OAuth20AccessTokenControllerTests#verifyRefreshTokenBadCredentials()

View license
@Test
public void verifyRefreshTokenBadCredentials() throws Exception {
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final RefreshToken refreshToken = addRefreshToken(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

59. AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    getThrottle().preHandle(request, response, null);
    getThrottle().postHandle(request, response, null, null);
    return response;
}

60. InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    getThrottle().preHandle(request, response, null);
    try {
        authenticationManager.authenticate(AuthenticationTransaction.wrap(TestUtils.getService(), badCredentials(username)));
    } catch (final AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AbstractAuthenticationException");
    return null;
}

61. OAuth20AccessTokenControllerTests#verifyNoCasService()

View license
@Test
public void verifyNoCasService() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    when(servicesManager.getAllServices()).thenReturn(new ArrayList<RegisteredService>());
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

62. OAuth20AccessTokenControllerTests#verifyRedirectUriDoesNotStartWithServiceId()

View license
@Test
public void verifyRedirectUriDoesNotStartWithServiceId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(OTHER_REDIRECT_URI, CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

63. OAuth20AccessTokenControllerTests#verifyWrongSecret()

View license
@Test
public void verifyWrongSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, WRONG_CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

64. OAuth20AccessTokenControllerTests#verifyNoServiceTicket()

View license
@Test
public void verifyNoServiceTicket() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    when(ticketRegistry.getTicket(CODE)).thenReturn(null);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_GRANT, mockResponse.getContentAsString());
}

65. OAuth20AccessTokenControllerTests#verifyExpiredServiceTicket()

View license
@Test
public void verifyExpiredServiceTicket() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ServicesManager servicesManager = mock(ServicesManager.class);
    final List<RegisteredService> services = new ArrayList<>();
    services.add(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));
    when(servicesManager.getAllServices()).thenReturn(services);
    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    final ServiceTicket serviceTicket = mock(ServiceTicket.class);
    when(serviceTicket.isExpired()).thenReturn(true);
    when(ticketRegistry.getTicket(CODE)).thenReturn(serviceTicket);
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setServicesManager(servicesManager);
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.afterPropertiesSet();
    oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(400, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_GRANT, mockResponse.getContentAsString());
}

66. AuthenticationViaFormActionTests#verifySuccessfulAuthenticationWithNoServiceAndWarn()

View license
@Test
public void verifySuccessfulAuthenticationWithNoServiceAndWarn() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putLoginTicket(context, "LOGIN");
    request.addParameter("lt", "LOGIN");
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);
    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("success", this.action.submit(context, c, messageContext).getId());
    assertNotNull(WebUtils.getTicketGrantingTicketId(context));
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}

67. AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    getThrottle().preHandle(request, response, null);
    getThrottle().postHandle(request, response, null, null);
    return response;
}

68. InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));
    getThrottle().preHandle(request, response, null);
    try {
        authenticationManager.authenticate(badCredentials(username));
    } catch (final AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AuthenticationException");
    return null;
}

69. AuthenticationViaFormActionTests#verifySuccessfulAuthenticationWithServiceAndWarn()

View license
@Test
public void verifySuccessfulAuthenticationWithServiceAndWarn() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockRequestContext context = new MockRequestContext();
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    request.addParameter("warn", "true");
    request.addParameter("service", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
    final Credential c = org.apereo.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);
    assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, this.action.doExecute(context).getId());
    assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName()));
}

70. AuthenticationViaFormActionTests#verifyRenewWithServiceAndSameCredentials()

View license
@Test
public void verifyRenewWithServiceAndSameCredentials() throws Exception {
    final Credential c = org.apereo.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Service service = TestUtils.getService(TestUtils.CONST_TEST_URL);
    final AuthenticationResult ctx = org.apereo.cas.authentication.TestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), service, c);
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();
    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", TestUtils.getService(TestUtils.CONST_TEST_URL).getId());
    request.addParameter("username", "test");
    request.addParameter("password", "test");
    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
    context.getFlowScope().put("service", TestUtils.getService());
    assertEquals(CasWebflowConstants.TRANSITION_ID_WARN, this.action.doExecute(context).getId());
}

71. OAuth20AccessTokenControllerTests#verifyClientNoClientId()

View license
//
//
// authorization code grant type tests
//
//
@Test
public void verifyClientNoClientId() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

72. OAuth20AccessTokenControllerTests#verifyClientNoRedirectUri()

View license
@Test
public void verifyClientNoRedirectUri() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

73. OAuth20AccessTokenControllerTests#verifyClientNoAuthorizationCode()

View license
@Test
public void verifyClientNoAuthorizationCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

74. OAuth20AccessTokenControllerTests#verifyClientNoClientSecret()

View license
@Test
public void verifyClientNoClientSecret() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final OAuthCode code = addCode(principal, service);
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

75. OAuth20AccessTokenControllerTests#verifyClientNoCode()

View license
@Test
public void verifyClientNoCode() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    addCode(principal, service);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

76. OAuth20AccessTokenControllerTests#verifyUserNoCasService()

View license
@Test
public void verifyUserNoCasService() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

77. OAuth20AccessTokenControllerTests#verifyUserBadAuthorizationCode()

View license
@Test
public void verifyUserBadAuthorizationCode() throws Exception {
    addRegisteredService();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.AUTHORIZATION_CODE.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

78. OAuth20AccessTokenControllerTests#verifyUserBadCredentials()

View license
@Test
public void verifyUserBadCredentials() throws Exception {
    addRegisteredService();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, "badPassword");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

79. OAuth20AccessTokenControllerTests#verifyRefreshTokenExpiredToken()

View license
//
//
// refresh token grant type tests
//
//
@Test
public void verifyRefreshTokenExpiredToken() throws Exception {
    final Principal principal = createPrincipal();
    final RegisteredService registeredService = addRegisteredService();
    final Authentication authentication = getAuthentication(principal);
    final Service service = new OAuthWebApplicationService(registeredService);
    final DefaultRefreshTokenFactory expiringRefreshTokenFactory = new DefaultRefreshTokenFactory();
    expiringRefreshTokenFactory.setExpirationPolicy(new AlwaysExpiresExpirationPolicy());
    final RefreshToken refreshToken = expiringRefreshTokenFactory.create(service, authentication);
    oAuth20AccessTokenController.getTicketRegistry().addTicket(refreshToken);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_GRANT, mockResponse.getContentAsString());
}

80. OAuth20AccessTokenControllerTests#verifyRefreshTokenBadCredentials()

View license
@Test
public void verifyRefreshTokenBadCredentials() throws Exception {
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final RefreshToken refreshToken = addRefreshToken(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuthGrantType.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}

81. AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    getThrottle().preHandle(request, response, null);
    getThrottle().postHandle(request, response, null, null);
    return response;
}

82. InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests#loginUnsuccessfully()

View license
@Override
protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("POST");
    request.setParameter("username", username);
    request.setRemoteAddr(fromAddress);
    final MockRequestContext context = new MockRequestContext();
    context.setCurrentEvent(new Event("", "error"));
    request.setAttribute("flowRequestContext", context);
    ClientInfoHolder.setClientInfo(new ClientInfo(request));
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    getThrottle().preHandle(request, response, null);
    try {
        authenticationManager.authenticate(AuthenticationTransaction.wrap(TestUtils.getService(), badCredentials(username)));
    } catch (final AuthenticationException e) {
        getThrottle().postHandle(request, response, null, null);
        return response;
    }
    fail("Expected AbstractAuthenticationException");
    return null;
}

83. ProxyRequestHelperTests#debug()

View license
@Test
public void debug() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
    request.setContent("{}".getBytes());
    request.addHeader("singleName", "singleValue");
    request.addHeader("multiName", "multiValue1");
    request.addHeader("multiName", "multiValue2");
    RequestContext.getCurrentContext().setRequest(request);
    TraceProxyRequestHelper helper = new TraceProxyRequestHelper();
    this.traceRepository = new InMemoryTraceRepository();
    helper.setTraces(this.traceRepository);
    MultiValueMap<String, String> headers = helper.buildZuulRequestHeaders(request);
    helper.debug("POST", "http://example.com", headers, new LinkedMultiValueMap<String, String>(), request.getInputStream());
    Trace actual = this.traceRepository.findAll().get(0);
    System.err.println(actual.getInfo());
    assertThat((String) actual.getInfo().get("body"), equalTo("{}"));
}

84. RetryWithHttpEntryPointTests#testNormalOperation()

View license
@Test
public void testNormalOperation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
    request.setQueryString("open=true");
    request.setScheme("https");
    request.setServerName("www.example.com");
    request.setServerPort(443);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
    ep.setPortMapper(new PortMapperImpl());
    ep.setPortResolver(new MockPortResolver(80, 443));
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
}

85. RetryWithHttpEntryPointTests#testOperationWhenTargetPortIsUnknown()

View license
@Test
public void testOperationWhenTargetPortIsUnknown() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
    request.setQueryString("open=true");
    request.setScheme("https");
    request.setServerName("www.example.com");
    request.setServerPort(8768);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
    ep.setPortMapper(new PortMapperImpl());
    ep.setPortResolver(new MockPortResolver(8768, 1234));
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
}

86. RetryWithHttpEntryPointTests#testOperationWithNonStandardPort()

View license
@Test
public void testOperationWithNonStandardPort() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
    request.setQueryString("open=true");
    request.setScheme("https");
    request.setServerName("www.example.com");
    request.setServerPort(9999);
    MockHttpServletResponse response = new MockHttpServletResponse();
    PortMapperImpl portMapper = new PortMapperImpl();
    Map<String, String> map = new HashMap<String, String>();
    map.put("8888", "9999");
    portMapper.setPortMappings(map);
    RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
    ep.setPortResolver(new MockPortResolver(8888, 9999));
    ep.setPortMapper(portMapper);
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true");
}

87. RetryWithHttpsEntryPointTests#testNormalOperation()

View license
@Test
public void testNormalOperation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
    request.setQueryString("open=true");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setServerPort(80);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
    ep.setPortMapper(new PortMapperImpl());
    ep.setPortResolver(new MockPortResolver(80, 443));
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
}

88. RetryWithHttpsEntryPointTests#testOperationWhenTargetPortIsUnknown()

View license
@Test
public void testOperationWhenTargetPortIsUnknown() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
    request.setQueryString("open=true");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setServerPort(8768);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
    ep.setPortMapper(new PortMapperImpl());
    ep.setPortResolver(new MockPortResolver(8768, 1234));
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
}

89. RetryWithHttpsEntryPointTests#testOperationWithNonStandardPort()

View license
@Test
public void testOperationWithNonStandardPort() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
    request.setQueryString("open=true");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setServerPort(8888);
    MockHttpServletResponse response = new MockHttpServletResponse();
    PortMapperImpl portMapper = new PortMapperImpl();
    Map<String, String> map = new HashMap<String, String>();
    map.put("8888", "9999");
    portMapper.setPortMappings(map);
    RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
    ep.setPortResolver(new MockPortResolver(8888, 9999));
    ep.setPortMapper(portMapper);
    ep.commence(request, response);
    assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
}

90. LogoutHandlerTests#testRequiresLogoutUrlWorksWithQueryParams()

View license
@Test
public void testRequiresLogoutUrlWorksWithQueryParams() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/context");
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setServletPath("/logout");
    request.setRequestURI("/context/logout?param=blah");
    request.setQueryString("otherparam=blah");
    assertThat(filter.requiresLogout(request, response)).isTrue();
}

91. ConnectSupportTest#buildOAuthUrl_OAuth10_withApplicationUrlAndNonDefaultServletPath()

View license
@Test
public void buildOAuthUrl_OAuth10_withApplicationUrlAndNonDefaultServletPath() throws Exception {
    ConnectSupport support = new ConnectSupport();
    support.setApplicationUrl("http://somehost:8080/spring-social-showcase");
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setServletPath("/foo");
    mockRequest.setPathInfo("/connect/someprovider");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    String url = support.buildOAuthUrl(new TestOAuth1ConnectionFactory(OAuth1Version.CORE_10), request);
    assertEquals("https://serviceprovider.com/oauth/authorize?oauth_callback=http://somehost:8080/spring-social-showcase/foo/connect/someprovider", url);
}

92. ConnectSupportTest#buildOAuthUrl_OAuth10a_withAdditionalParametersFromRequest()

View license
@Test
public void buildOAuthUrl_OAuth10a_withAdditionalParametersFromRequest() {
    ConnectSupport support = new ConnectSupport();
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setRequestURI("/connect/someprovider");
    mockRequest.addParameter("condiment", "ketchup");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    MultiValueMap<String, String> additionalParameters = new LinkedMultiValueMap<String, String>();
    additionalParameters.set("display", "popup");
    String url = support.buildOAuthUrl(new TestOAuth1ConnectionFactory(OAuth1Version.CORE_10_REVISION_A), request, additionalParameters);
    assertEquals("https://serviceprovider.com/oauth/authorize?display=popup&condiment=ketchup", url);
}

93. ConnectSupportTest#buildOAuthUrl_OAuth2_withApplicationUrlAndNonDefaultServletPath()

View license
@Test
public void buildOAuthUrl_OAuth2_withApplicationUrlAndNonDefaultServletPath() throws Exception {
    ConnectSupport support = new ConnectSupport();
    support.setApplicationUrl("https://someothersite.com:1234/spring-social-showcase");
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setServletPath("/foo");
    mockRequest.setPathInfo("/connect/someprovider");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    String url = support.buildOAuthUrl(new TestOAuth2ConnectionFactory(), request);
    assertEquals("https://serviceprovider.com/oauth/authorize?redirect_uri=https://someothersite.com:1234/spring-social-showcase/foo/connect/someprovider&state=STATE", url);
}

94. ConnectSupportTest#buildOAuthUrl_OAuth2_withAdditionalParametersFromRequest()

View license
@Test
public void buildOAuthUrl_OAuth2_withAdditionalParametersFromRequest() throws Exception {
    ConnectSupport support = new ConnectSupport();
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setRequestURI("/connect/someprovider");
    mockRequest.addParameter("condiment", "ketchup");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    TestOAuth2ConnectionFactory connectionFactory = new TestOAuth2ConnectionFactory();
    MultiValueMap<String, String> additionalParameters = new LinkedMultiValueMap<String, String>();
    additionalParameters.set("display", "popup");
    String url = support.buildOAuthUrl(connectionFactory, request, additionalParameters);
    assertEquals("https://serviceprovider.com/oauth/authorize?display=popup&condiment=ketchup&redirect_uri=http://somesite.com/connect/someprovider&state=STATE", url);
}

95. ConnectSupportTest#completeConnection_OAuth1()

View license
@Test
public void completeConnection_OAuth1() {
    ConnectSupport support = new ConnectSupport();
    MockHttpServletRequest mockRequest = new PortAwareMockHttpServletRequest();
    mockRequest.addParameter("oauth_verifier", "verifier");
    mockRequest.getSession().setAttribute("oauthToken", new OAuthToken("requestToken", "requestTokenSecret"));
    mockRequest.setScheme("http");
    mockRequest.setServerName("somesite.com");
    mockRequest.setRequestURI("/connect/someprovider");
    ServletWebRequest request = new ServletWebRequest(mockRequest);
    Connection<?> connection = support.completeConnection(new TestOAuth1ConnectionFactory(OAuth1Version.CORE_10_REVISION_A), request);
    assertEquals("TestUser", connection.getDisplayName());
    assertEquals("http://someprovider.com/images/testuser.jpg", connection.getImageUrl());
    assertEquals("http://someprovider.com/testuser", connection.getProfileUrl());
}

96. WebSphereParametersTest#testPostParametersFilter()

Project: wink
Source File: WebSphereParametersTest.java
View license
/*
     * Test POST (+GET) parameters.
     */
public void testPostParametersFilter() throws Exception {
    // create mock servlet objects
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setQueryString("a&b=&c=1&c=2");
    request.setContentType(WebSphereParametersFilter.CONTENT_TYPE_WWW_FORM_URLENCODED);
    request.setContent("d&e=&f=1&f=2".getBytes());
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();
    // test query parameters before parsing
    assertEquals("Query parameters are not empty before parsing", 0, request.getParameterMap().size());
    // invoke filter
    new WebSphereParametersFilter().doFilter(request, response, chain);
    // test query and POST parameters
    assertEquals("There are not 6 query parameters", 6, chain.getRequest().getParameterMap().size());
    assertParameters(chain.getRequest(), "a", "b", "c");
    assertParameters(chain.getRequest(), "d", "e", "f");
}

97. AbstractWebDAVResourcesTest#constructPropfindRequest()

View license
protected static MockHttpServletRequest constructPropfindRequest(Propfind propfind, String requestURI, int depth) throws IOException {
    MockHttpServletRequest mockRequest = new MockHttpServletRequestWrapper() {

        public String getPathTranslated() {
            // prevent Spring to resolve the file on the file
            return null;
        // system which fails
        }
    };
    // headers
    mockRequest.setMethod(WebDAVMethod.PROPFIND.name());
    mockRequest.setRequestURI(requestURI);
    mockRequest.setContentType(MediaType.APPLICATION_XML);
    if (depth >= 0) {
        mockRequest.addHeader(WebDAVHeaders.DEPTH, String.valueOf(depth));
    }
    // body
    StringWriter writer = new StringWriter();
    Propfind.marshal(propfind, writer);
    mockRequest.setContent(writer.toString().getBytes());
    return mockRequest;
}

98. RssFeedServletTest#testInvalidRequest()

Project: archiva
Source File: RssFeedServletTest.java
View license
@Test
public void testInvalidRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/feeds?invalid_param=xxx");
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod("GET");
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    rssFeedServlet.doGet(request, mockHttpServletResponse);
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, mockHttpServletResponse.getStatus());
}

99. AuthenticationFilterPathMatchingTest#testHttpBasicAuthenticationCheck()

View license
@Test
public void testHttpBasicAuthenticationCheck() throws IOException, ServletException {
    if (authenticationExpected) {
        when(identityServiceMock.checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD)).thenReturn(true);
    }
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(SERVICE_PATH + servletPath + requestUrl);
    request.setContextPath(SERVICE_PATH);
    request.setServletPath(servletPath);
    applyFilter(request, response, MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD);
    Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus());
    if (authenticationExpected) {
        verify(identityServiceMock).setAuthentication(MockProvider.EXAMPLE_USER_ID, groupIds, tenantIds);
        verify(identityServiceMock).clearAuthentication();
    } else {
        verify(identityServiceMock, never()).setAuthentication(any(String.class), anyListOf(String.class), anyListOf(String.class));
        verify(identityServiceMock, never()).clearAuthentication();
    }
}

100. WebApplicationServiceFactoryTests#verifyServiceCreationSuccessfullyByTargetServiceAndTicket()

View license
@Test
public void verifyServiceCreationSuccessfullyByTargetServiceAndTicket() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(CasProtocolConstants.PARAMETER_TARGET_SERVICE, "test");
    request.addParameter(CasProtocolConstants.PARAMETER_TICKET, "ticket");
    request.addParameter(CasProtocolConstants.PARAMETER_METHOD, "post");
    final WebApplicationServiceFactory factory = new WebApplicationServiceFactory();
    final WebApplicationService service = factory.createService(request);
    assertNotNull(service);
    assertEquals(service.getArtifactId(), "ticket");
}