@Test
  public void testFilterProcessesUrlVariationsRespected() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    request.setServletPath("/j_OTHER_LOCATION");
    request.setRequestURI("/mycontext/j_OTHER_LOCATION");

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will not be invoked, as we redirect to
    // defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
    filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
    filter.setAuthenticationSuccessHandler(successHandler);

    // Test
    filter.doFilter(request, response, chain);
    assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertEquals(
        "test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
  }
  @Test
  public void logoutUrl() throws Exception {
    request.setServletPath("/j_spring_security_logout");

    filter.doFilter(request, response, chain);

    assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
  }
  private MockHttpServletRequest createMockAuthenticationRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setServletPath("/j_mock_post");
    request.setScheme("http");
    request.setServerName("www.example.com");
    request.setRequestURI("/mycontext/j_mock_post");
    request.setContextPath("/mycontext");

    return request;
  }
  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");

    assertTrue(filter.requiresLogout(request, response));
  }
  public void testRequiresLogoutUrlWorksWithPathParams() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();

    request.setRequestURI("/context/logout;someparam=blah?param=blah");
    request.setServletPath("/logout;someparam=blah");
    request.setQueryString("otherparam=blah");

    DefaultHttpFirewall fw = new DefaultHttpFirewall();
    assertTrue(filter.requiresLogout(fw.getFirewalledRequest(request), response));
  }
Ejemplo n.º 6
0
  protected void testGetI18nData(Locale locale, I18nServlet.I18nData expectedI18nData)
      throws Exception {

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setPathInfo(StringPool.SLASH);
    mockHttpServletRequest.setServletPath(StringPool.SLASH + LocaleUtil.toLanguageId(locale));

    I18nServlet.I18nData actualI18nData = _i18nServlet.getI18nData(mockHttpServletRequest);

    Assert.assertEquals(expectedI18nData, actualI18nData);
  }
  /* Tests if service errors if the path should not be exposed.
   */
  @Test
  public final void testService_pathNotServed() throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockServletConfig config = new MockServletConfig();

    ContentModuleServlet servlet = new ContentModuleServlet(cache);
    servlet.init(config);

    request.setServletPath("/com/globant/katari/jsmodule/view/notserved/a.png");
    request.setMethod("GET");
    servlet.service(request, response);

    assertThat(response.getStatus(), is(404));
  }
Ejemplo n.º 8
0
 private MockHttpServletRequest buildMock(String completeUrl, String contextPath) {
   try {
     URI uri = new URI(completeUrl);
     MockServletContext context = new MockServletContext();
     context.setContextPath(contextPath);
     MockHttpServletRequest httpRequest =
         new MockHttpServletRequest(context, "get", uri.getPath());
     httpRequest.setLocalName(uri.getHost());
     httpRequest.setServerName(uri.getHost());
     httpRequest.setServletPath(
         completeUrl.substring(completeUrl.indexOf(contextPath) + contextPath.length()));
     httpRequest.setContextPath(contextPath);
     httpRequest.setServerPort(uri.getPort());
     return httpRequest;
   } catch (URISyntaxException e) {
     return null;
   }
 }
  /** Tests {@link PrefixLinkPostProcessor#prependBaseUri} */
  @Test
  public void testPrependBaseUri() {

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContextPath("/context");
    request.setServletPath("/servlet");
    ViewUtils.setBaseUri(request, true);

    PrefixLinkPostProcessor testling = new PrefixLinkPostProcessor();

    // 1.) expecting that base uri is prepended
    UriComponents uri = UriComponentsBuilder.fromUriString("/path/name.html").build();
    assertEquals(
        "prepended to absolute uri",
        "/context/servlet/path/name.html",
        ((UriComponentsBuilder) testling.prependBaseUri(uri, new Object(), null, request))
            .build()
            .toUriString());
  }
  @Test
  public void testIgnoresAnyServletPathOtherThanFilterProcessesUrl() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    request.setServletPath("/some.file.html");
    request.setRequestURI("/mycontext/some.file.html");

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will be invoked, as our request is for a page the
    // filter isn't monitoring
    MockFilterChain chain = new MockFilterChain(true);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to deny access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(false);

    // Test
    filter.doFilter(request, response, chain);
  }
  /* Tests if service correctly dispatches the request for a bundled
   * file which was cached.
   */
  @Test
  public final void testService_bundlePathFile() throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockServletConfig config = new MockServletConfig();

    String content = "var testFunction;";
    expect(cache.findContent("md5_hash_key.js")).andReturn(content);
    replay(cache);

    ContentModuleServlet servlet = new ContentModuleServlet(cache);
    servlet.init(config);

    request.setServletPath("/com/globant/katari/jsmodule/bundle/md5_hash_key.js");
    request.setMethod("GET");
    servlet.service(request, response);

    assertThat(response.getStatus(), is(200));
    assertThat(response.getContentType(), is("text/javascript"));
    assertThat(response.getContentAsString(), is(content));

    verify(cache);
  }
Ejemplo n.º 12
0
  public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVStorage webDAVStorage = new DLWebDAVStorageImpl();

    webDAVStorage.setToken("document_library");

    WebDAVUtil.addStorage(webDAVStorage);

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {
      mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
      Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
      headers = new HashMap<String, String>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
      throw new Exception();
    } catch (Exception e) {
      StackTraceElement[] stackTraceElements = e.getStackTrace();

      for (StackTraceElement stackTraceElement : stackTraceElements) {
        String methodName = stackTraceElement.getMethodName();

        if (methodName.equals("setUp")
            || methodName.equals("tearDown")
            || methodName.startsWith("test")) {

          String testName =
              StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

          testName =
              StringUtil.replace(testName, new String[] {"WebDAV", "Test"}, new String[] {"", ""});

          headers.put(
              "X-Litmus",
              testName
                  + ": ("
                  + stackTraceElement.getMethodName()
                  + ":"
                  + stackTraceElement.getLineNumber()
                  + ")");

          break;
        }
      }
    }

    if (data != null) {
      mockHttpServletRequest.setContent(data);

      String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

      if (contentType != null) {
        mockHttpServletRequest.setContentType(contentType);
      } else {
        mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
      }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();

      mockHttpServletRequest.addHeader(key, value);
    }

    try {
      MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

      webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

      int statusCode = mockHttpServletResponse.getStatus();
      byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

      Map<String, String> responseHeaders = new HashMap<String, String>();

      for (String name : mockHttpServletResponse.getHeaderNames()) {
        responseHeaders.put(name, (String) mockHttpServletResponse.getHeader(name));
      }

      return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }