public void testDoFilterNotAuthenticated() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameterNames())
          .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
      filter.init(config);

      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
      Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));

      HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

      FilterChain chain = Mockito.mock(FilterChain.class);

      Mockito.doAnswer(
              new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                  fail();
                  return null;
                }
              })
          .when(chain)
          .doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject());

      filter.doFilter(request, response, chain);

      Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } finally {
      filter.destroy();
    }
  }
Ejemplo n.º 2
0
 /** {@inheritDoc} */
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   final List<String> parameterNames = Collections.list(filterConfig.getInitParameterNames());
   for (final String parameterName : parameterNames) {
     customResources.put(parameterName, filterConfig.getInitParameter(parameterName));
   }
 }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    // 不放入session的跳转页面中
    String failure = this.errorPage;

    for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements(); ) {
      String headerName = (String) e.nextElement();
      httpResponse.addHeader(headerName, filterConfig.getInitParameter(headerName));
    }

    try {
      Enumeration e = request.getParameterNames();
      while (e.hasMoreElements()) {
        String parameterName = e.nextElement().toString();
        String value = request.getParameter(parameterName);
        if (!StringHelper.isNullString(value)) {
          if (this.webfilter) FilterManager.filter((String) value, new WebFilter());
          if (this.sqlfilter) FilterManager.filter((String) value, new SqlFilter());
          if (this.specialfilter) FilterManager.filter((String) value, new SpecialCharFilter());
        }
      }

      chain.doFilter(request, httpResponse);
    } catch (Exception e) {
      logger.info("安全过滤信息:" + e.getMessage());
      httpResponse.getWriter().write(e.getMessage());
    }
  }
Ejemplo n.º 4
0
    /**
     * Create new FilterConfigPropertyValues.
     *
     * @param config FilterConfig we'll use to take PropertyValues from
     * @param requiredProperties set of property names we need, where we can't accept default values
     * @throws ServletException if any required properties are missing
     */
    public FilterConfigPropertyValues(FilterConfig config, Set requiredProperties)
        throws ServletException {

      Set missingProps =
          (requiredProperties != null && !requiredProperties.isEmpty())
              ? new HashSet(requiredProperties)
              : null;

      Enumeration en = config.getInitParameterNames();
      while (en.hasMoreElements()) {
        String property = (String) en.nextElement();
        Object value = config.getInitParameter(property);
        addPropertyValue(new PropertyValue(property, value));
        if (missingProps != null) {
          missingProps.remove(property);
        }
      }

      // Fail if we are still missing properties.
      if (missingProps != null && missingProps.size() > 0) {
        throw new ServletException(
            "Initialization from FilterConfig for filter '"
                + config.getFilterName()
                + "' failed; the following required properties were missing: "
                + StringUtils.collectionToDelimitedString(missingProps, ", "));
      }
    }
  /**
   * Initialize this filter.
   *
   * @param config <code>FilterConfig</code>
   */
  public void init(final FilterConfig config) {
    this.context = config.getServletContext();
    this.requireAttribute =
        Boolean.valueOf(config.getInitParameter(REQUIRE_ATTRIBUTE)).booleanValue();
    if (LOG.isDebugEnabled()) {
      LOG.debug("requireAttribute = " + this.requireAttribute);
    }

    final Enumeration<?> e = config.getInitParameterNames();
    while (e.hasMoreElements()) {
      final String name = (String) e.nextElement();
      if (!name.equals(REQUIRE_ATTRIBUTE)) {
        final String value = config.getInitParameter(name);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Loaded attribute name:value " + name + ":" + value);
        }

        final StringTokenizer st = new StringTokenizer(name);
        final String attrName = st.nextToken();
        final String attrValue = st.nextToken();

        this.attributes.put(attrName, Pattern.compile(attrValue));
        this.redirects.put(attrName, value);
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Stored attribute "
                  + attrName
                  + " for pattern "
                  + attrValue
                  + " with redirect of "
                  + value);
        }
      }
    }
  }
  public void testGetToken() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET))
          .thenReturn("secret");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(
              new Vector(
                      Arrays.asList(
                          AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET))
                  .elements());
      filter.init(config);

      AuthenticationToken token =
          new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
      token.setExpires(System.currentTimeMillis() + 1000);
      Signer signer = new Signer("secret".getBytes());
      String tokenSigned = signer.sign(token.toString());

      Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
      Mockito.when(request.getCookies()).thenReturn(new Cookie[] {cookie});

      AuthenticationToken newToken = filter.getToken(request);

      assertEquals(token.toString(), newToken.toString());
    } finally {
      filter.destroy();
    }
  }
Ejemplo n.º 7
0
    public Enumeration<String> getInitParameterNames() {
      Set<String> result = Sets.newLinkedHashSet();

      result.addAll(Collections.list(filterConfig.getInitParameterNames()));
      result.addAll(Collections.list(filterConfig.getServletContext().getInitParameterNames()));

      return Iterators.asEnumeration(result.iterator());
    }
Ejemplo n.º 8
0
 @Override
 public final void init(FilterConfig config) throws ServletException {
   Enumeration<String> parameterNames = config.getInitParameterNames();
   while (parameterNames.hasMoreElements()) {
     String name = parameterNames.nextElement();
     headers.put(name, config.getInitParameter(name));
   }
 }
Ejemplo n.º 9
0
 private Map<String, String> filterConfigToMap(FilterConfig filterConfig) {
   Map<String, String> configMap = new HashMap<String, String>();
   Enumeration params = filterConfig.getInitParameterNames();
   while (params.hasMoreElements()) {
     String paramName = (String) params.nextElement();
     configMap.put(paramName, filterConfig.getInitParameter(paramName));
   }
   return configMap;
 }
  public void testGetConfiguration() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    FilterConfig config = Mockito.mock(FilterConfig.class);
    Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("");
    Mockito.when(config.getInitParameter("a")).thenReturn("A");
    Mockito.when(config.getInitParameterNames())
        .thenReturn(new Vector(Arrays.asList("a")).elements());
    Properties props = filter.getConfiguration("", config);
    assertEquals("A", props.getProperty("a"));

    config = Mockito.mock(FilterConfig.class);
    Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo");
    Mockito.when(config.getInitParameter("foo.a")).thenReturn("A");
    Mockito.when(config.getInitParameterNames())
        .thenReturn(new Vector(Arrays.asList("foo.a")).elements());
    props = filter.getConfiguration("foo.", config);
    assertEquals("A", props.getProperty("a"));
  }
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   @SuppressWarnings("unchecked")
   Enumeration<String> paramNames = filterConfig.getInitParameterNames();
   while (paramNames.hasMoreElements()) {
     String paramName = paramNames.nextElement();
     String paramValue = filterConfig.getInitParameter(paramName);
     if ("allow-anonymous".equalsIgnoreCase(paramName))
       allowAnonymous = Boolean.parseBoolean(paramValue);
   }
 }
Ejemplo n.º 12
0
 public ApplicationConfig(FilterConfig config) {
   parameterNames = new ArrayList<String>();
   this.config = config;
   this.servletConfig = null;
   servletContext = config.getServletContext();
   if (config == null) return;
   Enumeration en = config.getInitParameterNames();
   while (en.hasMoreElements()) {
     parameterNames.add((String) en.nextElement());
   }
 }
Ejemplo n.º 13
0
 private void initParams(FilterConfig config) {
   securityResources = new HashMap<String, Set<String>>();
   for (Enumeration<String> e = config.getInitParameterNames(); e.hasMoreElements(); ) {
     String urlPattern = e.nextElement();
     String[] roles = config.getInitParameter(urlPattern).split(",");
     Set<String> rolesSet = new HashSet<String>();
     for (String role : roles) {
       rolesSet.add(role);
     }
     securityResources.put(urlPattern, rolesSet);
   }
 }
Ejemplo n.º 14
0
  /** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */
  @SuppressWarnings("unchecked")
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletResponse res = (HttpServletResponse) response;
    // set the provided HTTP response parameters
    for (Enumeration<String> e = fc.getInitParameterNames(); e.hasMoreElements(); ) {
      String headerName = e.nextElement();
      res.addHeader(headerName, fc.getInitParameter(headerName));
    }
    // pass the request/response on
    chain.doFilter(request, response);
  }
Ejemplo n.º 15
0
 /**
  * Returns the filtered configuration (only properties starting with the specified prefix). The
  * property keys are also trimmed from the prefix. The returned {@link Properties} object is used
  * to initialized the {@link AuthenticationHandler}.
  *
  * <p>This method can be overriden by subclasses to obtain the configuration from other
  * configuration source than the web.xml file.
  *
  * @param configPrefix configuration prefix to use for extracting configuration properties.
  * @param filterConfig filter configuration object
  * @return the configuration to be used with the {@link AuthenticationHandler} instance.
  * @throws ServletException thrown if the configuration could not be created.
  */
 protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig)
     throws ServletException {
   Properties props = new Properties();
   Enumeration<?> names = filterConfig.getInitParameterNames();
   while (names.hasMoreElements()) {
     String name = (String) names.nextElement();
     if (name.startsWith(configPrefix)) {
       String value = filterConfig.getInitParameter(name);
       props.put(name.substring(configPrefix.length()), value);
     }
   }
   return props;
 }
 public void testInitEmpty() throws Exception {
   AuthenticationFilter filter = new AuthenticationFilter();
   try {
     FilterConfig config = Mockito.mock(FilterConfig.class);
     Mockito.when(config.getInitParameterNames()).thenReturn(new Vector().elements());
     filter.init(config);
     fail();
   } catch (ServletException ex) {
     // Expected
   } catch (Exception ex) {
     fail();
   } finally {
     filter.destroy();
   }
 }
Ejemplo n.º 17
0
 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
     throws IOException, ServletException {
   HttpServletResponse response = (HttpServletResponse) res;
   // set the provided HTTP response parameters
   for (Enumeration e = fc.getInitParameterNames(); e.hasMoreElements(); ) {
     String headerName = (String) e.nextElement();
     response.addHeader(headerName, fc.getInitParameter(headerName));
   }
   // pass the request/response on
   try {
     chain.doFilter(req, response);
   } catch (Throwable ex) {
     log.error(ex.getMessage(), ex);
     ex.printStackTrace();
   }
 }
Ejemplo n.º 18
0
 public void init(FilterConfig filterConfig) throws ServletException {
   this.filterConfig = filterConfig;
   expiresMap.clear();
   Enumeration names = filterConfig.getInitParameterNames();
   while (names.hasMoreElements()) {
     try {
       final String name = (String) names.nextElement();
       final String value = filterConfig.getInitParameter(name);
       final Integer expire = Integer.valueOf(value);
       expiresMap.put(name, expire);
     } catch (Exception e) {
       LOGGER.log(Level.SEVERE, "Error while init the CacheFilter in session");
       throw new ServletException(e);
     }
   }
 }
Ejemplo n.º 19
0
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   Enumeration<String> paramNames = filterConfig.getInitParameterNames();
   while (paramNames.hasMoreElements()) {
     String paramName = paramNames.nextElement();
     if (!IntrospectionUtils.setProperty(
         this, paramName, filterConfig.getInitParameter(paramName))) {
       String msg =
           sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName());
       if (isConfigProblemFatal()) {
         throw new ServletException(msg);
       } else {
         getLogger().warn(msg);
       }
     }
   }
 }
  public void testDoFilterAuthenticated() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameterNames())
          .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
      filter.init(config);

      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
      Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));

      AuthenticationToken token = new AuthenticationToken("u", "p", "t");
      token.setExpires(System.currentTimeMillis() + 1000);
      Signer signer = new Signer("alfredo".getBytes());
      String tokenSigned = signer.sign(token.toString());

      Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
      Mockito.when(request.getCookies()).thenReturn(new Cookie[] {cookie});

      HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

      FilterChain chain = Mockito.mock(FilterChain.class);

      Mockito.doAnswer(
              new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                  Object[] args = invocation.getArguments();
                  HttpServletRequest request = (HttpServletRequest) args[0];
                  assertEquals("u", request.getRemoteUser());
                  assertEquals("p", request.getUserPrincipal().getName());
                  return null;
                }
              })
          .when(chain)
          .doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject());

      filter.doFilter(request, response, chain);

    } finally {
      filter.destroy();
    }
  }
Ejemplo n.º 21
0
  /**
   * Place this filter into service.
   *
   * @param filterConfig The filter configuration object
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    if (filterConfig == null) {
      throw new IllegalArgumentException("FilterConfig must not be null.");
    }

    for (Enumeration<String> e = filterConfig.getInitParameterNames(); e.hasMoreElements(); ) {
      String initParam = e.nextElement();
      if (initParam.startsWith(INIT_PARAM_HTTP_HEADER_PREFIX)) {
        httpHeaders.put(
            initParam.substring(INIT_PARAM_HTTP_HEADER_PREFIX.length()),
            filterConfig.getInitParameter(initParam));
      } else if (initParam.equals(INIT_PARAM_URI_REGEXP)) {
        this.uriRegexp = Pattern.compile(filterConfig.getInitParameter(INIT_PARAM_URI_REGEXP));
      } else {
        throw new ServletException("Not a valid parameter: " + initParam);
      }
    }
  }
  public void testGetRequestURL() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameterNames())
          .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
      filter.init(config);

      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
      Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
      Mockito.when(request.getQueryString()).thenReturn("a=A&b=B");

      assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request));
    } finally {
      filter.destroy();
    }
  }
  @BeforeMethod
  private void initAuthType() {
    ConcurrentHashMap<String, String> conf = new ConcurrentHashMap<String, String>();
    conf.put("type", "simple");
    conf.put("config.prefix.type", "");
    conf.put("anonymous.allowed", "true");
    ServletContext servletContext = Mockito.mock(ServletContext.class);
    Mockito.when(mockConfig.getInitParameterNames()).thenReturn(conf.keys());
    Mockito.when(mockConfig.getServletContext()).thenReturn(servletContext);

    for (Map.Entry<String, String> entry : conf.entrySet()) {
      Mockito.when(mockConfig.getInitParameter(entry.getKey())).thenReturn(entry.getValue());
    }

    Mockito.when(mockRequest.getMethod()).thenReturn("OPTIONS");

    StringBuffer requestUrl = new StringBuffer("http://localhost");
    Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
  }
  /**
   * Updates the configuration from the filter config.
   *
   * @param filterConfig
   */
  @SuppressWarnings("unchecked")
  public void updateConfigration(FilterConfig filterConfig) {
    Enumeration<String> paramEnum = filterConfig.getInitParameterNames();
    while (paramEnum.hasMoreElements()) {
      String paramName = paramEnum.nextElement();
      if (paramName.startsWith("r")) {
        try {
          if (!runOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          runOptions.put(paramName, Boolean.parseBoolean(filterConfig.getInitParameter(paramName)));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if (paramName.startsWith("b")) {
        try {
          if (!batchOptions.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          batchOptions.put(paramName, Integer.parseInt(filterConfig.getInitParameter(paramName)));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if (paramName.startsWith("p")) {
        try {
          if (!parameterNames.containsKey(paramName)) throw new Exception("Invalid Parameter Name");
          parameterNames.put(paramName, filterConfig.getInitParameter(paramName));
        } catch (Exception e) {
          log.warn("Init Parameter [" + paramName + "] is invalid or could not be set.", e);
        }
      } else if ("listenerClassName".equals(paramName)) {
        listenerClassName = filterConfig.getInitParameter(paramName);
      } else if ("agentLogLevel".equals(paramName)) {
        try {
          agentLogLevel = Integer.parseInt(filterConfig.getInitParameter(paramName));
        } catch (Exception e) {
          log.warn("Agent Log Level Could Not Be Set. Defaulting to [" + agentLogLevel + "].", e);
        }

      } else {
        log.warn("Init Parameter [" + paramName + "] was not recognized.");
      }
    }
    log.info("Completed AjaxMetrics Filter Configuration. Config is:\n" + toString());
    inited = true;
  }
Ejemplo n.º 25
0
 public void init(FilterConfig filterConfig) {
   this.config = filterConfig;
   this.encoding = config.getInitParameter("encoding");
   if (encoding == null || encoding.length() == 0) {
     encoding = "GBK";
   }
   expiresMap = new HashMap();
   Enumeration names = config.getInitParameterNames();
   while (names.hasMoreElements()) {
     String paramName = (String) names.nextElement();
     if (!"encoding".equals(paramName)) {
       String paramValue = config.getInitParameter(paramName);
       try {
         Integer expires = Integer.valueOf(config.getInitParameter(paramName));
         expiresMap.put(paramName, expires);
       } catch (Exception ex) {
         // LogUtil.logError( "Filter."+paramValue+"="+paramValue);
       }
     }
   }
 }
  @Override
  public void init(final FilterConfig webXmlConfig) throws ServletException {
    Preconditions.checkNotNull(properties, "Must inject @CasFilterProperties Properties");
    final HashMap<String, String> filterInitParameters = Maps.newHashMap();

    List<String> initParameterNames = list(webXmlConfig.getInitParameterNames());
    for (String initParameterName : initParameterNames) {
      filterInitParameters.put(initParameterName, webXmlConfig.getInitParameter(initParameterName));
    }

    for (String initParameterName : casFilterInitParameterNames) {
      if (!Strings.isNullOrEmpty(properties.getProperty(initParameterName)))
        filterInitParameters.put(initParameterName, properties.getProperty(initParameterName));
    }

    FilterConfig filterConfig =
        new FilterConfig() {
          @Override
          public String getFilterName() {
            return webXmlConfig.getFilterName();
          }

          @Override
          public ServletContext getServletContext() {
            return webXmlConfig.getServletContext();
          }

          @Override
          public String getInitParameter(String name) {
            return filterInitParameters.get(name);
          }

          @Override
          public Enumeration<String> getInitParameterNames() {
            return Collections.enumeration(filterInitParameters.keySet());
          }
        };

    super.init(filterConfig);
  }
Ejemplo n.º 27
0
  /** Gets init-params from web.xml This is called synchronized by the servlet container. */
  public void init(FilterConfig filterConfig) {
    System.out.println(Version.LOGO_ASCIIART);
    applicationContext = filterConfig.getServletContext();
    String appName = applicationContext.getContextPath().replace("/", "");
    applicationContext.setAttribute(APP_NAME_KEY, appName);

    Configuration.init(appName);

    @SuppressWarnings("rawtypes")
    Enumeration names = filterConfig.getInitParameterNames();
    while (names.hasMoreElements()) {
      String key = (String) names.nextElement();
      initParams.put(key, filterConfig.getInitParameter(key));
    }

    /* init velocity
     * name of properties file is determined from
     * a) System Property <contextname>.velocity.configuration
     * b) System Property <PREFIX>.velocity.configuration
     * c) velocity.properties
     * d) default-fallback-velocity.properties
     */
    try {
      ClassLoader cl = this.getClass().getClassLoader();
      Properties velocityProperties =
          Dispatcher.readProperties(
              System.getProperty(appName + SYSTEM_PROPERTY_VELOCITY_PROPS_SUFFIX),
              System.getProperty(PREFIX + SYSTEM_PROPERTY_VELOCITY_PROPS_SUFFIX),
              "/velocity.properties");
      if (velocityProperties.isEmpty()) {
        velocityProperties = new Properties();
        velocityProperties.load(cl.getResourceAsStream("default-fallback-velocity.properties"));
      }
      velocityEngine = new VelocityEngine(velocityProperties);
      /* init velocity tool manager -- automatically finds all default-tools, the framework's tools as defined in tools.xml and all tools of the web-app specified in tools.xml at classpath-root. */
      velocityToolManager = new ViewToolManager(applicationContext, false, false);
      velocityToolManager.setVelocityEngine(velocityEngine);
      velocityToolManager.autoConfigure(true);
    } catch (Exception e) {
      log.fatal("velocity init failed!");
      log.fatalException(e);
    }

    String languages = getInitParam(PARAM_LANGUAGES);
    String[] supported;
    if (languages == null) {
      supported = new String[] {"en"};
    } else {
      supported = languages.split("\\s*,\\s*");
      if (supported == null || supported.length == 0) {
        supported = new String[] {"en"};
      }
    }
    supportedLanguages = Arrays.asList(supported);

    try {
      collectControllers();
    } catch (Exception e) {
      log.error("Collecting Controllers and Actions failed.");
      log.errorException(e);
    }
  }
Ejemplo n.º 28
0
 @Override
 protected Enumeration initParamNames() {
   return config.getInitParameterNames();
 }
  public void testInit() throws Exception {

    // minimal configuration & simple auth handler (Pseudo)
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TOKEN_VALIDITY))
          .thenReturn("1000");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(
              new Vector(
                      Arrays.asList(
                          AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.AUTH_TOKEN_VALIDITY))
                  .elements());
      filter.init(config);
      assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
      assertTrue(filter.isRandomSecret());
      assertNull(filter.getCookieDomain());
      assertNull(filter.getCookiePath());
      assertEquals(1000, filter.getValidity());
    } finally {
      filter.destroy();
    }

    // custom secret
    filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
      Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET))
          .thenReturn("secret");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(
              new Vector(
                      Arrays.asList(
                          AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET))
                  .elements());
      filter.init(config);
      assertFalse(filter.isRandomSecret());
    } finally {
      filter.destroy();
    }

    // custom cookie domain and cookie path
    filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
      Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_DOMAIN))
          .thenReturn(".foo.com");
      Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)).thenReturn("/bar");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(
              new Vector(
                      Arrays.asList(
                          AuthenticationFilter.AUTH_TYPE,
                          AuthenticationFilter.COOKIE_DOMAIN,
                          AuthenticationFilter.COOKIE_PATH))
                  .elements());
      filter.init(config);
      assertEquals(".foo.com", filter.getCookieDomain());
      assertEquals("/bar", filter.getCookiePath());
    } finally {
      filter.destroy();
    }

    // authentication handler lifecycle, and custom impl
    DummyAuthenticationHandler.reset();
    filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameterNames())
          .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
      filter.init(config);
      assertTrue(DummyAuthenticationHandler.init);
    } finally {
      filter.destroy();
      assertTrue(DummyAuthenticationHandler.destroy);
    }

    // kerberos auth handler
    filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("kerberos");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
      filter.init(config);
    } catch (ServletException ex) {
      // Expected
    } finally {
      assertEquals(
          KerberosAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
      filter.destroy();
    }
  }
  private void _testDoFilterAuthentication(boolean withDomainPath) throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
      FilterConfig config = Mockito.mock(FilterConfig.class);
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
          .thenReturn(DummyAuthenticationHandler.class.getName());
      Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TOKEN_VALIDITY))
          .thenReturn("1000");
      Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET))
          .thenReturn("secret");
      Mockito.when(config.getInitParameterNames())
          .thenReturn(
              new Vector(
                      Arrays.asList(
                          AuthenticationFilter.AUTH_TYPE,
                          AuthenticationFilter.AUTH_TOKEN_VALIDITY,
                          AuthenticationFilter.SIGNATURE_SECRET))
                  .elements());

      if (withDomainPath) {
        Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_DOMAIN))
            .thenReturn(".foo.com");
        Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)).thenReturn("/bar");
        Mockito.when(config.getInitParameterNames())
            .thenReturn(
                new Vector(
                        Arrays.asList(
                            AuthenticationFilter.AUTH_TYPE,
                            AuthenticationFilter.AUTH_TOKEN_VALIDITY,
                            AuthenticationFilter.SIGNATURE_SECRET,
                            AuthenticationFilter.COOKIE_DOMAIN,
                            AuthenticationFilter.COOKIE_PATH))
                    .elements());
      }

      filter.init(config);

      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
      Mockito.when(request.getParameter("authenticated")).thenReturn("true");
      Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
      Mockito.when(request.getQueryString()).thenReturn("authenticated=true");

      HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

      FilterChain chain = Mockito.mock(FilterChain.class);

      final boolean[] calledDoFilter = new boolean[1];

      Mockito.doAnswer(
              new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                  calledDoFilter[0] = true;
                  return null;
                }
              })
          .when(chain)
          .doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject());

      final Cookie[] setCookie = new Cookie[1];
      Mockito.doAnswer(
              new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                  Object[] args = invocation.getArguments();
                  setCookie[0] = (Cookie) args[0];
                  return null;
                }
              })
          .when(response)
          .addCookie(Mockito.<Cookie>anyObject());

      filter.doFilter(request, response, chain);

      assertNotNull(setCookie[0]);
      assertEquals(AuthenticatedURL.AUTH_COOKIE, setCookie[0].getName());
      assertTrue(setCookie[0].getValue().contains("u="));
      assertTrue(setCookie[0].getValue().contains("p="));
      assertTrue(setCookie[0].getValue().contains("t="));
      assertTrue(setCookie[0].getValue().contains("e="));
      assertTrue(setCookie[0].getValue().contains("s="));
      assertTrue(calledDoFilter[0]);

      Signer signer = new Signer("secret".getBytes());
      String value = signer.verifyAndExtract(setCookie[0].getValue());
      AuthenticationToken token = AuthenticationToken.parse(value);
      assertEquals(System.currentTimeMillis() + 1000 * 1000, token.getExpires(), 100);

      if (withDomainPath) {
        assertEquals(".foo.com", setCookie[0].getDomain());
        assertEquals("/bar", setCookie[0].getPath());
      } else {
        assertNull(setCookie[0].getDomain());
        assertNull(setCookie[0].getPath());
      }
    } finally {
      filter.destroy();
    }
  }