コード例 #1
0
ファイル: WebdavFixFilter.java プロジェクト: hqmshhxx/tomcat8
  /**
   * Check for the broken MS WebDAV client and if detected issue a re-direct that hopefully will
   * cause the non-broken client to be used.
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
      chain.doFilter(request, response);
      return;
    }
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    HttpServletResponse httpResponse = ((HttpServletResponse) response);
    String ua = httpRequest.getHeader("User-Agent");

    if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) {
      // No UA or starts with non MS value
      // Hope everything just works...
      chain.doFilter(request, response);
    } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) {
      // XP 32-bit SP3 - needs redirect with explicit port
      httpResponse.sendRedirect(buildRedirect(httpRequest));
    } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) {
      // XP 64-bit SP2
      if (!"".equals(httpRequest.getContextPath())) {
        log(request, "XP-x64-SP2 clients only work with the root context");
      }
      // Namespace issue maybe
      // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html
      log(request, "XP-x64-SP2 is known not to work with WebDAV Servlet");

      chain.doFilter(request, response);
    } else {
      // Don't know which MS client it is - try the redirect with an
      // explicit port in the hope that it moves the client to a different
      // WebDAV implementation that works
      httpResponse.sendRedirect(buildRedirect(httpRequest));
    }
  }
コード例 #2
0
ファイル: AutoLoginFilter.java プロジェクト: Tagin/aurora-ide
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    HttpSession session = request.getSession();
    Object user_login = session.getAttribute(AURORA_USER_LOGIN);
    if (user_login != null) {
      filterChain.doFilter(request, response);
      return;
    }
    SapUserDistil distil = new SapUserDistil();
    try {
      String loginName = distil.execute(request, verifyPseFile, logger);
      if (loginName == null) {
        filterChain.doFilter(request, response);
        return;
      }
      executeLoginProc(request, response, loginName);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "", e);
      return;
    }
    session.setAttribute(AURORA_USER_LOGIN, Boolean.TRUE);
    if (afterLoginRedirectUrl != null) response.sendRedirect(afterLoginRedirectUrl);
  }
コード例 #3
0
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String relativeUrl = request.getRequestURI(); /* 以根开头的URL */
    String path = request.getContextPath(); /* 获取客户端请求的上下文根 */

    /** 如果是登录请求,则进行登录认证。 如果是其它请求,则进行IP绑定匹配。 */
    if (relativeUrl.replaceAll(path, "").equals("/login")) { // 登录请求,登录认证
      if (request.getMethod().equals("POST")) { // 登录参数必须通过post方式传过来,security要求的
        int status = myAuthentication.getAuthenticationStatus(request); // 调用认证逻辑
        if (status == 0) { // 通过认证,则保存登录IP到session,并通过此过滤器
          request.getSession().setAttribute("bindIp", RequestIP.getRequestIp(request));
          chain.doFilter(request, response);
        } else { // 未通过认证,则拒绝登录,并返回登录页面提示相关信息
          response.sendRedirect(path + "/toIndex.action?error=" + status);
        }
      } else { // 如果不是POST方式,则返回登录页面,并提示信息
        response.sendRedirect(path + "/toIndex.action?error=9"); // 登录必须用POST方式
      }
    } else { // 其它请求(filters="none"的请求不会被处理,logout请求在此filter之前会被处理)
      // PC端进行IP认证
      String loginIp = (String) request.getSession().getAttribute("bindIp"); // 登录时记录的IP
      String currentIp = RequestIP.getRequestIp(request); // 当前请求的IP
      if (loginIp != null && !loginIp.equals(currentIp)) { // 如果此次请求的IP与登录IP不符,则禁止访问,并返回提示
        response.sendRedirect(path + "/toIndex.action?error=10");
      } else { // 如果IP匹配,则通过此过滤器
        chain.doFilter(request, response);
      }
    }
  }
コード例 #4
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    // Another type of auth
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    if (httpServletRequest.getRequestURI().contains(AuthController.AUTHENTICATED_TOKENS)) {
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }

    // Success
    String header = httpServletRequest.getHeader("Authorization");
    if (header != null
        && header.startsWith(TOKEN_PREFIX)
        && header.substring(TOKEN_PREFIX.length()).trim().equals(token)) {
      //            SecurityContextHolder.getContext().setAuthentication(createAuth());
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }

    // Or error
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
  }
コード例 #5
0
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (judgeIsMoblie(request)) {
      chain.doFilter(req, resp);
      return;
    }
    Object userId = request.getSession().getAttribute("userId");
    String requestURI = request.getRequestURI();

    if (isContinue(requestURI)) {
      chain.doFilter(req, resp);
      return;
    }

    if (null != userId) { // 只有登录验证成功(session还存在时),才继续
      chain.doFilter(req, resp);
    } else { //        否则 用户界面,自动弹出窗口提示用户输入登录账号,登录成功后可以继续使用本系统
      HttpServletResponse response = (HttpServletResponse) resp;
      String header = request.getHeader("x-requested-with");
      if ("XMLHttpRequest".equals(header)) {
        response.setStatus(401);
        //                response.setHeader("status", "401");
        PrintWriter writer = response.getWriter();
        writer.print("请重新登录");
        writer.flush();
        //                Map<String, Object> map = new HashMap<String, Object>();
        //                W.writeJsonObject(map);
      } else {
        chain.doFilter(req, resp);
      }
    }
  }
コード例 #6
0
  /*
   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse, javax.servlet.FilterChain)
   */
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    if (domainCross) {
      response.addHeader("Access-Control-Allow-Origin", "*");
      response.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
      response.addHeader("Access-Control-Allow-Credentials", "true");
      response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
      response.addHeader("Access-Control-Max-Age", "600000");
    }

    // jsonp
    if (RestConstant.REQ_METHOD_GET.equals(request.getMethod())) {
      String callBack = request.getParameter(RestConstant.RESP_CALLBACK);
      if (StringUtils.isNotEmpty(callBack)) {
        ResourceResponseWrapper wapper = new ResourceResponseWrapper(response);
        chain.doFilter(req, wapper);
        byte[] json = wapper.getResponseData();
        StringBuffer jsonStr = new StringBuffer(new String(json, "UTF-8"));
        jsonStr.insert(0, callBack + "(");
        jsonStr.append(")");
        ServletOutputStream output = response.getOutputStream();
        output.write(jsonStr.toString().getBytes("UTF-8"));
        output.flush();
      } else {
        chain.doFilter(req, response);
      }
    } else {
      chain.doFilter(req, response);
    }
  }
コード例 #7
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String host = req.getHeader("Host").trim();
    // System.out.println(host);
    int indexOf = host.indexOf(":");
    host = host.substring(0, indexOf);
    boolean startsWith = host.endsWith(DOMAIN);
    // System.out.println(startsWith);

    String url = req.getPathInfo();
    if (null == url) {
      url = req.getServletPath();
      System.out.println("url>>>>:" + url);
      if (url.endsWith(".css")) {
        chain.doFilter(request, response);
        return;
      }
    }
    if (startsWith) {
      int index = host.indexOf(DOMAIN);
      String hostname = host.substring(0, index);
      // System.out.println(index);
      // System.out.println(hostname);
      String forwardUrl = urls.get(hostname);
      req.getRequestDispatcher(forwardUrl).forward(req, resp);
      return;
    }

    chain.doFilter(request, response);
  }
コード例 #8
0
  public static void doFilter(
      ServletRequest request, ServletResponse response, FilterChain next, boolean isSecure)
      throws ServletException, IOException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    /*
    if (res instanceof CauchoResponse) {
      // server/125i - XXX: needs refactor
      CauchoResponse cRes = (CauchoResponse) res;
      CauchoRequest oldReq = cRes.getAbstractHttpResponse().getRequest();

      cRes.getAbstractHttpResponse().setRequest((CauchoRequest) req);
      try {
        next.doFilter(req, res);
      } finally {
        cRes.getAbstractHttpResponse().setRequest(oldReq);
      }
    }
    */

    if (req instanceof HttpServletRequestImpl) {
      HttpServletRequestImpl requestFacade = (HttpServletRequestImpl) req;

      requestFacade.setSecure(true);

      // XXX: finally

      next.doFilter(req, res);
    } else {
      req = new SecureServletRequestWrapper(req, isSecure);

      next.doFilter(req, res);
    }
  }
コード例 #9
0
  @Test
  public void testGetFilterChain() throws Exception {
    mockBundleWiring();

    CaptureHandler captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(), Level.INFO);

    try {
      List<LogRecord> logRecords = captureHandler.getLogRecords();

      String cssFilterName = "CSS Filter";

      registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

      String jsFilterName = "JS Filter";

      registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

      FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js");

      Assert.assertNotNull(filterChain);

      filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

      Assert.assertEquals(1, logRecords.size());

      LogRecord logRecord = logRecords.get(0);

      Assert.assertEquals(jsFilterName, logRecord.getMessage());

      verifyBundleWiring();
    } finally {
      captureHandler.close();
    }
  }
コード例 #10
0
ファイル: LoginFilter.java プロジェクト: hulu2002/ims
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    //		String basePath = request.getContextPath() + "/";
    // URL基本路径
    //		String basePath = request.getScheme() + "://"+request.getServerName() + ":"
    //		+ request.getServerPort() + request.getContextPath() + "/";
    RequestDispatcher dispatcher = req.getRequestDispatcher("login.jsp");
    HttpSession session = request.getSession(true);

    // 从session中获取路径和用户名
    String path = request.getRequestURI();
    String username = (String) session.getAttribute("username");

    if (path.indexOf("/login.jsp") > -1 || path.indexOf("relogin.jsp") > -1) {
      chain.doFilter(request, response);
      return;
    }

    // 判断是否已经登录
    if (username == null || "".equals(username)) {
      // 尚未登录,跳转到登录页面
      // dispatcher.forward(req, res);
      response.sendRedirect("/ims/relogin.jsp");
    } else {
      // 已经登录,继续此次请求
      chain.doFilter(request, response);
    }
  }
コード例 #11
0
ファイル: GzipFilter.java プロジェクト: yuri0x7c1/opentaps-1
 /** {@inheritDoc} */
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) req;
   HttpServletResponseWrapper response =
       new HttpServletResponseWrapper((HttpServletResponse) resp);
   String encoding = request.getHeader("Accept-Encoding");
   boolean supportsGzip = false;
   // Now, check to see if the browser supports the GZIP compression
   if (encoding != null) {
     if (encoding.toLowerCase().indexOf("gzip") > -1) supportsGzip = true;
   }
   Debug.log(
       "supportsGzip : "
           + supportsGzip
           + ", encoding : "
           + encoding
           + ", requestURL : "
           + request.getRequestURL());
   if (supportsGzip) {
     // add content encoding
     response.setHeader("Content-Encoding", "gzip");
     GzipResponse compressionResponse = new GzipResponse(response);
     chain.doFilter(request, compressionResponse);
     compressionResponse.close();
   } else {
     chain.doFilter(req, resp);
   }
 }
コード例 #12
0
ファイル: SessionFilter.java プロジェクト: pkaq/CMS
  /**
   * @param request the current request
   * @param response the current response
   * @param chain the chain
   * @throws IOException when something goes wrong
   * @throws ServletException when a communication failure happens
   */
  @SuppressWarnings("unchecked")
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpSession session = request.getSession();
    String request_uri = request.getRequestURI();
    // System.out.println("request_uri===="+request_uri);
    long sessionAccessedTime = session.getLastAccessedTime();
    long mySessionTime = 0;
    if (session.getAttribute("mySessionTime") != null)
      mySessionTime = Long.parseLong(session.getAttribute("mySessionTime").toString());

    // if(request_uri.indexOf("login.html")==-1&&request_uri.indexOf("out.html")==-1){//sessionMonitoring
    // System.out.println("==1=="+request.getContextPath()+"/error.jsp");
    // response.sendRedirect(request.getContextPath()+"/admin/sessionError.html");
    if (request_uri.indexOf("noticeLoadDesktopNotice.html") == -1
        && request_uri.indexOf("noticeLoadUnReadedNotice.html") == -1
        && request_uri.indexOf("sessionMonitoring.html") == -1) {
      session.setAttribute("mySessionTime", sessionAccessedTime);
      chain.doFilter(request, response);
    } else {
      // System.out.println("sessionAccessedTime===="+sessionAccessedTime);
      // System.out.println("mySessionTime===="+mySessionTime);
      chain.doFilter(request, response);
    }
  }
コード例 #13
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Cliente cliente = (Cliente) httpRequest.getSession().getAttribute("usuarioLogado");

    String paginaAcessada = httpRequest.getRequestURI();
    boolean requestDoLogin = paginaAcessada.contains("login.xhtml");

    if (cliente != null) {
      if (requestDoLogin) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendRedirect("index.xhtml");
      } else {
        chain.doFilter(request, response);
      }
    } else {
      if (!requestDoLogin && !paginaAcessada.contains("javax.faces.resource")) {
        httpRequest.getRequestDispatcher("/login.xhtml").forward(request, response);
      } else {
        chain.doFilter(request, response);
      }
    }
  }
コード例 #14
0
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try {
      prepare.setEncodingAndLocale(request, response);
      prepare.createActionContext(request, response);
      prepare.assignDispatcherToThread();
      if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
        chain.doFilter(request, response);
      } else {
        request = prepare.wrapRequest(request);
        ActionMapping mapping = prepare.findActionMapping(request, response, true);
        if (mapping == null) {
          boolean handled = execute.executeStaticResourceRequest(request, response);
          if (!handled) {
            chain.doFilter(request, response);
          }
        } else {
          execute.executeAction(request, response, mapping);
        }
      }
    } finally {
      prepare.cleanupRequest(request);
    }
  }
コード例 #15
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
      throw new ServletException("Only HttpServletRequest requests are supported");
    }

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

    // extract the callback method from the request query parameters
    String callback = getCallbackMethod(httpRequest);

    if (!isJSONPRequest(callback)) {
      // Request is not a JSONP request move on
      chain.doFilter(request, response);
    } else {
      // Need to check if the callback method is safe
      if (!SAFE_PRN.matcher(callback).matches()) {
        throw new ServletException(
            "JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
      }

      // Will stream updated response
      final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      // Create a custom response wrapper to adding in the padding
      HttpServletResponseWrapper responseWrapper =
          new HttpServletResponseWrapper(httpResponse) {

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
              return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                  byteStream.write(b);
                }
              };
            }

            @Override
            public PrintWriter getWriter() throws IOException {
              return new PrintWriter(byteStream);
            }
          };

      // Process the rest of the filter chain, including the JAX-RS request
      chain.doFilter(request, responseWrapper);

      // Override response content and encoding
      response.setContentType(CONTENT_TYPE);
      response.setCharacterEncoding("UTF-8");

      // Write the padded updates to the output stream.
      response.getOutputStream().write((callback + "(").getBytes());
      response.getOutputStream().write(byteStream.toByteArray());
      response.getOutputStream().write(");".getBytes());
    }
  }
コード例 #16
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession();
    Object loginUserInforObj = session.getAttribute(Common_util.LOGIN_USER);

    if (loginUserInforObj != null) {
      UserInfor loginUserInfor = (UserInfor) loginUserInforObj;
      String requestURL = req.getRequestURI();
      //		    System.out.println(requestURL);
      String requestFunction = requestURL.substring(requestURL.lastIndexOf("/action/") + 8);
      //		    System.out.println(requestFunction);

      // 1. check is it the default function for every one
      boolean isDefault = DefaultFunctionHeadQ.isDefaultFunction(requestFunction);
      if (isDefault) {
        chain.doFilter(request, response);
      } else {
        // 2. check whether the user has been granted the high level function
        boolean exist = loginUserInfor.getFunctions().contains(requestFunction);
        if (loginUserInfor.getRoleType() != 99 && !exist) {
          String originalURL = req.getContextPath() + "/jsp/common/unauthorizedAccess.jsp";
          loggerLocal.info("WARNING headq: unauthorized access to " + requestFunction);
          res.sendRedirect(originalURL);
        } else {
          chain.doFilter(request, response);
        }
      }

    } else {
      chain.doFilter(request, response);
    }
  }
コード例 #17
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      String requestUri = httpRequest.getRequestURI();
      String rootDir = getRootDir(requestUri);

      if (staticResourceDirs.contains(rootDir)) {
        // Static resource, not profiled
        chain.doFilter(request, response);
      } else {
        Profiler profiler = Profiler.createIfDebug(Logger).start();
        try {
          chain.doFilter(request, response);
        } finally {
          if (profiler.isDebugEnabled()) {
            String queryString = httpRequest.getQueryString();
            String message =
                String.format(
                    queryString == null ? MESSAGE_WITHOUT_QUERY : MESSAGE_WITH_QUERY,
                    httpRequest.getMethod(),
                    requestUri,
                    queryString);
            profiler.stopDebug(message);
          }
        }
      }
    } else {
      // Not an HTTP request, not profiled
      chain.doFilter(request, response);
    }
  }
コード例 #18
0
ファイル: XecureFilter.java プロジェクト: kwbaek/codelabor
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    XecureHttpServletRequest xecureHttpServletRequest = null;
    XecureHttpServletResponse xecureHttpServletResponse = null;

    String qValue = httpServletRequest.getParameter("q");
    if (log.isDebugEnabled()) {
      StringBuilder sb = new StringBuilder();
      sb.append("q: ").append(qValue);
      log.debug(sb.toString());
    }

    if (StringUtils.isEmpty(qValue)) {
      chain.doFilter(httpServletRequest, httpServletResponse);
    } else if (Boolean.parseBoolean(httpServletRequest.getParameter("fileEnc"))) {
      chain.doFilter(httpServletRequest, httpServletResponse);
    } else {
      try {
        XecureServlet xecureServlet =
            new XecureServlet(new XecureConfig(), httpServletRequest, httpServletResponse);
        xecureHttpServletRequest = xecureServlet.request;
        xecureHttpServletResponse = xecureServlet.response;
        chain.doFilter(xecureHttpServletRequest, xecureHttpServletResponse);
      } catch (XecureServletException e) {
        e.printStackTrace();
      } catch (XecureServletConfigException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #19
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // If the filter wasn't initialised then forward the request
    if (!enabled
        || !(request instanceof HttpServletRequest)
        || !(response instanceof HttpServletResponse)
        || isIncluded((HttpServletRequest) request)) {
      chain.doFilter(request, response);
      return;
    }

    // Check if the request will accept compression
    boolean supportCompression = false;
    Enumeration<String> e = ((HttpServletRequest) request).getHeaders("Accept-Encoding");
    while (e.hasMoreElements()) {
      final String headerName = e.nextElement();
      if (headerName.indexOf("gzip") != -1) {
        supportCompression = true;
      }
    }

    // Do the compression if it's supported otherwise continue down the chain
    if (!supportCompression) {
      chain.doFilter(request, response);
      return;
    } else {
      final GZIPResponseWrapper responseWrapper =
          new GZIPResponseWrapper((HttpServletResponse) response, mimeTypes);
      chain.doFilter(request, responseWrapper);
      responseWrapper.finish();
    }
  }
コード例 #20
0
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    if (SystemConfigs.get("memSessionSwitch", "true").equalsIgnoreCase("true")) {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
      HttpServletResponse response = (HttpServletResponse) servletResponse;
      String sid = request.getSession().getId();
      if (StringUtils.isNotBlank(request.getParameter("jsessionid"))) {
        String jsessionid = request.getParameter("jsessionid");
        if (!StringUtils.equals(sid, jsessionid)) {
          HttpSession session = request.getSession(false);
          if (session != null) session.invalidate();
          Cookie cookie = new Cookie("JSESSIONID", jsessionid);
          cookie.setDomain(request.getServerName());
          cookie.setPath("/");
          response.addCookie(cookie);
          sid = jsessionid;
        }
      }
      sessionLog.info("get session in memcached...");
      filterChain.doFilter(new HttpServletRequestWrapper(sid, request), servletResponse);
    } else {
      sessionLog.info("get session in httpsession...");
      filterChain.doFilter(servletRequest, servletResponse);
    }
  }
コード例 #21
0
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   HttpSession session = ((HttpServletRequest) request).getSession(true);
   Authn authnService =
       (Authn)
           WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
               .getBean(authnBean);
   String userUid = null;
   try {
     userUid = authnService.getUserUid(request);
   } catch (Exception e) {
     if (log.isDebugEnabled()) log.debug("Could not get user uuid from authn service.");
   }
   if (log.isDebugEnabled()) log.debug("userUid=" + userUid);
   if (userUid == null) {
     if (authnRedirect != null) {
       if (authnRedirect.equals(((HttpServletRequest) request).getRequestURI())) {
         // Don't redirect to the same spot.
         chain.doFilter(request, response);
       } else {
         ((HttpServletResponse) response).sendRedirect(authnRedirect);
       }
     } else {
       ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
     }
   } else {
     chain.doFilter(request, response);
   }
 }
コード例 #22
0
  @Override
  public void doFilter(
      final ServletRequest theRequest, final ServletResponse theResponse, final FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) theRequest;
    HttpServletResponse response = (HttpServletResponse) theResponse;
    String servletPath = request.getServletPath();

    if (captchaService == null) {
      captchaService = SpringContextUtils.getBean("captchaService");
    }

    if (servletPath.startsWith(filterProcessesUrl)) {
      if (filter) {
        boolean validated = validateCaptchaChallenge(request);
        if (validated) {
          chain.doFilter(request, response);
        } else {
          redirectFailureUrl(request, response);
        }
      } else {
        chain.doFilter(request, response);
      }
    } else {
      genernateCaptchaImage(request, response);
    }
  }
コード例 #23
0
ファイル: LoginFilter.java プロジェクト: agespucrs/audiolivro
  /** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = ((HttpServletRequest) request);

    /*
     * if (httpRequest.getRequestURI().endsWith("login.jsp")){
     * System.out.println("É uma jsp: " + httpRequest.getRequestURI()); }
     * else { System.out.println("NÃO é uma JSP: " +
     * httpRequest.getRequestURL()); }
     */

    String uri = httpRequest.getRequestURI();

    // trocado pelo método isURLToExclusao(uri) (!uri.endsWith("login.jsp") && !uri.endsWith(".css")

    if (!isURLToExclusao(uri, httpRequest)) {
      HttpSession session = httpRequest.getSession();
      if (session.getAttribute("usuarioSessao") == null) {
        request.setAttribute("msgAviso", MensagemContantes.MSG_INF_DENY);
        request.getRequestDispatcher("login.jsp").forward(request, response);
      } else {
        chain.doFilter(request, response);
      }
    } else {
      chain.doFilter(request, response);
    }
  }
コード例 #24
0
ファイル: MementoFilter.java プロジェクト: nandana/marmotta
  /**
   * appends memento timegate link to all resources, that are accessed via GET on resource
   * webservice
   *
   * @param servletRequest
   * @param servletResponse
   * @param filterChain
   * @throws IOException
   * @throws ServletException
   */
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
      HttpServletRequest request = (HttpServletRequest) servletRequest;

      // memento is only for reading
      if (request.getMethod().equals("GET") || request.getMethod().equals("HEAD")) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        URL resource = getResourceURL(request);

        // build timegate link
        if (resource != null) {
          response.addHeader(
              "Link",
              "<"
                  + MementoUtils.timegateURI(resource.toString(), configurationService.getBaseUri())
                  + ">; rel=\"timegate\","
                  + "<"
                  + MementoUtils.timemapURI(resource.toString(), configurationService.getBaseUri())
                  + ">; rel=\"timemap\"");
        }

        filterChain.doFilter(servletRequest, response);
        return;
      }
    }
    filterChain.doFilter(servletRequest, servletResponse);
  }
コード例 #25
0
  /** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String requestURI = ((HttpServletRequest) request).getRequestURI();
    if (requestURI.contains(redirectOnFailure)) {
      chain.doFilter(request, response);
    } else {
      HttpSession session =
          AuthorizationManager.getSessionAndCreate(request); // Create session if does not exist.
      String currentUser = (String) session.getAttribute("user");

      if (currentUser == null) {
        returnError(
            (HttpServletRequest) request,
            (HttpServletResponse) response,
            session,
            "Cannot find username information, please login!");
      } else {
        // Get relevant URI.
        String URI = ((HttpServletRequest) request).getRequestURI();

        // Invoke AuthorizationManager method to see if user can
        // access resource.
        boolean authorized = this.isUserAuthorized(currentUser, URI);
        if (!authorized) {
          returnError(
              (HttpServletRequest) request,
              (HttpServletResponse) response,
              session,
              "User is not authorized to access this area!");
        }
      }
      chain.doFilter(request, response);
    }
  }
コード例 #26
0
ファイル: TestFilter.java プロジェクト: kantega/superheroic
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;

    String uri = req.getRequestURI();
    String path = uri.substring(0, uri.lastIndexOf("/") + 1);
    String name = uri.substring(uri.lastIndexOf("/") + 1);

    File testFile = new File("src/main/resources/tests" + path + "test-" + name);
    if (req.getParameter("skiptest") == null && testFile.exists() && testFile.isFile()) {
      Wrapper wrapper = new Wrapper(resp);
      filterChain.doFilter(req, wrapper);
      resp.flushBuffer();

      if (wrapper.isWrapped()) {
        String content = new String(wrapper.toByteArray(), "utf-8");
        String test = IOUtils.toString(testFile.toURI().toURL(), "utf-8");
        content = content.replace("</body>", test + "</body>");
        resp.getOutputStream().print(content);
      }
    } else {
      filterChain.doFilter(req, resp);
    }
  }
コード例 #27
0
ファイル: AuthFilter.java プロジェクト: JavaAFei/score
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String uri = req.getRequestURI();

    log.info(req.getRemoteAddr() + "\tvisite\t" + uri);
    String project = req.getContextPath();
    /*if (SESSION_COMPANY == null && SESSION_BUYER == null && SESSION_BRANCH==null && !uri.endsWith(project+"/logout.do")) {
    	cookieLogin((HttpServletRequest)request, (HttpServletResponse)response);
    }*/
    if ((project + "/").equals(uri) || (project + "/index.jsp").equals(uri)) {
      res.sendRedirect(req.getContextPath() + "/index.do"); // 用户未登
    }

    if (isNeedCheck(uri, project)) {
      if (1 == 1) {
        // 如果toLogin参数存在,则登录以后跳回到原页面
        String toLogin = req.getParameter("toLogin");
        String returnURL = "";
        if (null != toLogin) returnURL = req.getHeader("Referer");
        // 用户未登
        res.sendRedirect(req.getContextPath() + "/login.jsp?returnURL=" + returnURL);
      } else {
        chain.doFilter(request, response);
      }
    } else {
      chain.doFilter(request, response);
    }
  }
コード例 #28
0
  @SuppressWarnings("unchecked")
  @Override
  public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest httpreq = (HttpServletRequest) req;

    if (FiltersHelper.isAuthenticated(httpreq)
        || httpreq.getAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY) != null) {
      chain.doFilter(req, rsp);
    } else {
      ((HttpServletRequest) req).setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes);
      HttpSession session = httpreq.getSession(false);
      Deque<AuthenticationProfile> stack = null;
      if (session != null) {
        stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR);
      }
      if (stack == null) {
        stack = new ArrayDeque<>();
        stack.addAll(profiles);
      }
      doAuth(httpreq, (HttpServletResponse) rsp, stack);
      if (!stack.isEmpty()) {
        httpreq.getSession(true).setAttribute(STACK_ATTR, stack);
      } else {
        if (session != null) {
          session.removeAttribute(STACK_ATTR);
        }
        chain.doFilter(req, rsp);
      }
    }
  }
コード例 #29
0
ファイル: Router.java プロジェクト: scanniza/webappar
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletRequest r = (HttpServletRequest) req;

    // Some info
    LOG.log(Level.INFO, "URL={0}", r.getRequestURL());
    LOG.log(Level.INFO, "URI={0}", r.getRequestURI());
    LOG.log(Level.INFO, "SERVLET PATH={0}", r.getServletPath());
    LOG.log(Level.INFO, "PATH INFO={0}", r.getPathInfo());
    LOG.log(Level.INFO, "QUERY={0}", r.getQueryString());
    LOG.log(Level.INFO, "--------------------------");

    String uri = r.getRequestURI();
    String path = r.getServletPath();
    try {
      // Pass through resources
      if (resources.matcher(uri).matches()) {
        chain.doFilter(req, res);
      } else if (path.equals("/") || path.equals("/home")) {
        req.getRequestDispatcher(TEMPLATE + "?partial=home").forward(req, res);
      } else {
        chain.doFilter(req, res);
      }
    } catch (IOException | ServletException ex) {
      LOG.log(Level.WARNING, ex.getMessage());
      try {
        req.setAttribute("error", ex.getMessage());
        req.getRequestDispatcher(TEMPLATE + "?partial=error").forward(req, res);
      } catch (ServletException | IOException ex1) {
        LOG.log(Level.SEVERE, ex1.getMessage());
      }
    }
  }
コード例 #30
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (_filtered) {
      Continuation c = (Continuation) request.getAttribute(Continuation.ATTRIBUTE);
      FilteredContinuation fc;
      if (_faux && (c == null || !(c instanceof FauxContinuation))) {
        fc = new FauxContinuation(request);
        request.setAttribute(Continuation.ATTRIBUTE, fc);
      } else fc = (FilteredContinuation) c;

      boolean complete = false;
      while (!complete) {
        try {
          if (fc == null || (fc).enter(response)) chain.doFilter(request, response);
        } catch (ContinuationThrowable e) {
          debug("faux", e);
        } finally {
          if (fc == null) fc = (FilteredContinuation) request.getAttribute(Continuation.ATTRIBUTE);

          complete = fc == null || (fc).exit();
        }
      }
    } else {
      try {
        chain.doFilter(request, response);
      } catch (ContinuationThrowable e) {
        debug("caught", e);
      }
    }
  }