Java Code Examples for javax.servlet.FilterChain.doFilter()

The following are Jave code examples for showing how to use doFilter() of the javax.servlet.FilterChain class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: buenojo   File: CsrfCookieGeneratorFilter.java   View Source Code Vote up 9 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example 2
Project: wisp   File: RequestFilter.java   View Source Code Vote up 7 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // 包装请求和响应
    if (LOGGER.isDebugEnabled()) {
        request = new RequestWrapper((HttpServletRequest) request);
        response = new ResponseWrapper((HttpServletResponse) response);
    }
    try {

        chain.doFilter(request, response);

    } finally {
        if (LOGGER.isDebugEnabled()) {
            // 进行打印
            logRequest((RequestWrapper) request);
            logResponse((ResponseWrapper) response);
        }
    }
}
 
Example 3
Project: tomcat7   File: TestStandardContext.java   View Source Code Vote up 7 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    out.print(getClass().getName());
    chain.doFilter(request, response);
}
 
Example 4
Project: elastic-job-cloud   File: WwwAuthFilter.java   View Source Code Vote up 7 votes
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String authorization = httpRequest.getHeader("authorization");
    if (null != authorization && authorization.length() > AUTH_PREFIX.length()) {
        authorization = authorization.substring(AUTH_PREFIX.length(), authorization.length());
        if ((rootUsername + ":" + rootPassword).equals(new String(Base64.decodeBase64(authorization)))) {
            authenticateSuccess(httpResponse, false);
            chain.doFilter(httpRequest, httpResponse);
        } else if ((guestUsername + ":" + guestPassword).equals(new String(Base64.decodeBase64(authorization)))) {
            authenticateSuccess(httpResponse, true);
            chain.doFilter(httpRequest, httpResponse);
        } else {
            needAuthenticate(httpResponse);
        }
    } else {
        needAuthenticate(httpResponse);
    }
}
 
Example 5
Project: tqdev-metrics   File: MeasureUserActivityFilter.java   View Source Code Vote up 6 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {
	if (!registry.isEnabled()) {
		filterChain.doFilter(request, response);
		return;
	}
	final long startTime = registry.getNanos();
	filterChain.doFilter(request, response);
	final long duration = registry.getNanos() - startTime;

	final String username = getUsername();
	registry.increment("spring.Username.Invocations", username);
	registry.add("spring.Username.Durations", username, duration);
}
 
Example 6
Project: apache-tomcat-7.0.73-with-comment   File: WsFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    // This filter only needs to handle WebSocket upgrade requests
    if (!sc.areEndpointsRegistered() ||
            !UpgradeUtil.isWebSocketUpgradeRequest(request, response)) {
        chain.doFilter(request, response);
        return;
    }

    // HTTP request with an upgrade header for WebSocket present
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    // Check to see if this WebSocket implementation has a matching mapping
    String path;
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        path = req.getServletPath();
    } else {
        path = req.getServletPath() + pathInfo;
    }
    WsMappingResult mappingResult = sc.findMapping(path);

    if (mappingResult == null) {
        // No endpoint registered for the requested path. Let the
        // application handle it (it might redirect or forward for example)
        chain.doFilter(request, response);
        return;
    }

    UpgradeUtil.doUpgrade(sc, req, resp, mappingResult.getConfig(),
            mappingResult.getPathParams());
}
 
Example 7
Project: intelijus   File: CacheControlFilter.java   View Source Code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    HttpServletResponse resp = (HttpServletResponse) response;
    resp.setHeader("Expires", "Tue, 03 Jul 2001 06:00:00 GMT");
    resp.setDateHeader("Last-Modified", new Date().getTime());
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    resp.setHeader("Pragma", "no-cache");

    chain.doFilter(request, response);
}
 
Example 8
Project: TorgCRM-Server   File: JWTFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    String jwt = resolveToken(httpServletRequest);
    if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
        Authentication authentication = this.tokenProvider.getAuthentication(jwt);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 9
Project: unitimes   File: NoCacheFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
	if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
		String agent = ((HttpServletRequest)request).getHeader("user-agent");
		if (agent != null && iUserAgent.matcher(agent).find())
			response = new HttpServletResponseWrapper((HttpServletResponse)response).createResponse();
	}
	chain.doFilter(request,response);
}
 
Example 10
Project: wormboard-backend   File: SimpleCORSFilter.java   View Source Code Vote up 6 votes
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
  throws IOException, ServletException
{
  HttpServletResponse response = (HttpServletResponse) res;
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "GET");
  response.setHeader("Access-Control-Max-Age", "3600");
  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
  chain.doFilter(req, res);
}
 
Example 11
Project: bumblebee   File: LoginFilter.java   View Source Code Vote up 6 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    requestURI = requestURI.replaceAll("/+", "/").replaceAll("/+", "/");
    LOG.info("LoginFilter receive request uri : " + requestURI);

    if (requestURI.equals("/")||requestURI.equals("/web/login")||requestURI.equals("/web/doLogin")||requestURI.startsWith("/resources")|| requestURI.startsWith("/terminal/")) {
        filterChain.doFilter(request, response);
        return;
    }
    String path = request.getContextPath();
    this.basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

    HttpSession session = request.getSession();

    BumblebeeUser user=(BumblebeeUser) session.getAttribute("curUser");
    if(null==user){
        java.io.PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<script>");
        out.println("window.open ('"+basePath+"','_top')");
        out.println("</script>");
        out.println("</html>");
    }else{
        filterChain.doFilter(request, response);
        return;
    }


}
 
Example 12
Project: pingguopai   File: TokenAuthenticationFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

    String authToken = tokenHelper.getToken(request);
    if (authToken != null && !skipPathRequest(request, pathsToSkip)) {
        // get username from token
        String username = null;
        try {
            username = tokenHelper.getUsernameFromToken(authToken);
            logger.info("[TokenAuthenticationFilter->doFilterInternal] authToken is {} and username is {}",
                        authToken,
                        username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                User user = cacheHelper.getSessionUser("session_" + username);
                if (cacheHelper.getSessionUser("session_" + username) == null) {
                    throw new BadCredentialsException("回话失效,请重新登录");
                }
                    // get user
                UserDetails userDetails = (UserDetails) user;//userDetailsService.loadUserByUsername(username);
                // create authentication
                TokenBasedAuthentication authentication = new TokenBasedAuthentication(userDetails);
                authentication.setToken(authToken);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            logger.error("[TokenAuthenticationFilter->doFilterInternal] authToken is {} and username is {};" +
                    " error:",
                    authToken, username, e);
            SecurityContextHolder.getContext().setAuthentication(new AnonAuthentication());
        }
    } else {
        SecurityContextHolder.getContext().setAuthentication(new AnonAuthentication());
    }
    chain.doFilter(request, response);
}
 
Example 13
Project: aem-osgi-annotation-demo   File: SampleFelixFilter.java   View Source Code Vote up 6 votes
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    logger.info("Felix Filter: request for {}", slingRequest.getRequestPathInfo().getResourcePath());

    filterChain.doFilter(request, response);
}
 
Example 14
Project: unitimes   File: HibSessionFilter.java   View Source Code Vote up 6 votes
/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(
        ServletRequest request, 
        ServletResponse response,
		FilterChain chain ) throws IOException, ServletException {
    
	if (filterConfig==null) return;
	
	if (request.getAttribute("TimeStamp")==null)
		request.setAttribute("TimeStamp", new Double(JProf.currentTimeSec()));
	
	try {
		// Process request
		chain.doFilter(request,response);

       	_BaseRootDAO.closeCurrentThreadSessions();
	} catch (Throwable ex) {
		_BaseRootDAO.rollbackCurrentThreadSessions();

           if (ex instanceof ServletException) throw (ServletException)ex;
           if (ex instanceof IOException) throw (IOException)ex;
		if (ex instanceof RuntimeException) throw (RuntimeException)ex;

           // Let others handle it... maybe another interceptor for exceptions?
           throw new ServletException(ex);
       }
		
}
 
Example 15
Project: lemon   File: OncePerRequestFilter.java   View Source Code Vote up 6 votes
/**
 * This {@code doFilter} implementation stores a request attribute for
 * "already filtered", proceeding without filtering again if the attribute is already
 * there.
 * @param request the request
 * @param response the response
 * @param filterChain the filter chain
 * @throws ServletException if request is not HTTP request
 * @throws IOException in case of I/O operation exception
 */
public final void doFilter(ServletRequest request, ServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	if (!(request instanceof HttpServletRequest)
			|| !(response instanceof HttpServletResponse)) {
		throw new ServletException(
				"OncePerRequestFilter just supports HTTP requests");
	}
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;
	boolean hasAlreadyFilteredAttribute = request
			.getAttribute(this.alreadyFilteredAttributeName) != null;

	if (hasAlreadyFilteredAttribute) {

		// Proceed without invoking this filter...
		filterChain.doFilter(request, response);
	}
	else {
		// Do invoke this filter...
		request.setAttribute(this.alreadyFilteredAttributeName, Boolean.TRUE);
		try {
			doFilterInternal(httpRequest, httpResponse, filterChain);
		}
		finally {
			// Remove the "already filtered" request attribute for this request.
			request.removeAttribute(this.alreadyFilteredAttributeName);
		}
	}
}
 
Example 16
Project: lams   File: SystemSessionFilter.java   View Source Code Vote up 6 votes
@Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
// Skip non-http request/response
if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) {
    chain.doFilter(request, response);
    return;
}

SessionManager.startSession((HttpServletRequest) request);
// do following part of chain
chain.doFilter(request, response);
SessionManager.endSession();
   }
 
Example 17
Project: ctsms   File: CharacterEncodingFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	chain.doFilter(request, response);
}
 
Example 18
Project: cas-5.1.0   File: AuthenticationCredentialsLocalBinderClearingFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(final ServletRequest servletRequest,
                     final ServletResponse servletResponse,
                     final FilterChain filterChain) throws IOException, ServletException {

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        AuthenticationCredentialsLocalBinder.clear();
    }
}
 
Example 19
Project: bxbot-ui-server   File: JwtAuthenticationFilter.java   View Source Code Vote up 5 votes
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    try {

        // Extract token after Bearer prefix if present
        String authorizationHeader = request.getHeader(AUTHORIZATION_HEADER);
        if (authorizationHeader != null && authorizationHeader.startsWith(BEARER_PREFIX)) {
            authorizationHeader = authorizationHeader.substring(BEARER_PREFIX_LENGTH);
        }

        // Might be null if client does not have a token yet
        if (authorizationHeader != null) {

            final Claims claims = jwtUtils.validateTokenAndGetClaims(authorizationHeader);
            final String username = jwtUtils.getUsernameFromTokenClaims(claims);
            LOG.info(() -> "Username in JWT: " + username);

            if (SecurityContextHolder.getContext().getAuthentication() == null) {

                // It is not compulsory to load the User details from the database.
                // We can just use the information in the token claims - this saves a repo lookup.
                //
                // final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // if (userDetails != null && !(userDetails.getUsername().equals(username))) {
                //    final String errorMsg = "Username is token not found in User repository! Token username: " + username;
                //    throw new JwtAuthenticationException(errorMsg);
                // }

                LOG.info(() -> "JWT is valid");

                // final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                //        userDetails, null, userDetails.getAuthorities());
                final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username, null, jwtUtils.getRolesFromTokenClaims(claims));

                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);

                LOG.info(() -> "Authenticated User: " + username + " has been set in Spring SecurityContext.");
            }
        }

        chain.doFilter(request, response);

    } catch (Exception e) {
        LOG.error("JWT Authentication failure! Details: " + e.getMessage(), e);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
 
Example 20
Project: oauth-filter-for-java   File: OAuthFilter.java   View Source Code Vote up 3 votes
/**
 * The doFilter is the primary filter method of a Servlet filter. It is implemented as a final method
 * and will call the configured filters authenticate and authorize methods.
 * Authorize is optional to implement as this filter implements a default scope check method.
 * @param servletRequest The default servlet request
 * @param servletResponse The default servlet response
 * @param filterChain A filter chain to continue with after this filter is done
 * @throws IOException
 * @throws ServletException
 */
@Override
public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException
{
    HttpServletResponse response = (HttpServletResponse)servletResponse;
    Optional<String> token = extractAccessTokenFromHeader(servletRequest);
    String oauthHost = getOAuthServerRealm();

    if (!token.isPresent())
    {
        setReAuthenticate401(response, oauthHost);

        return;
    }

    Optional<AuthenticatedUser> maybeAuthenticatedUser = authenticate(token.get());

    if (!maybeAuthenticatedUser.isPresent())
    {
        setReAuthenticate401(response, oauthHost);

        return;
    }

    AuthenticatedUser authenticatedUser = maybeAuthenticatedUser.get();

    if (!isAuthorized(authenticatedUser))
    {
        //403 Forbidden Scope header
        setForbidden403(response, oauthHost);

        return;
    }

    if (filterChain != null)
    {
        filterChain.doFilter(
                new AuthenticatedUserRequestWrapper((HttpServletRequest)servletRequest, authenticatedUser),
                servletResponse);
    }
}