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

The following examples show how to use javax.servlet.FilterChain#doFilter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestContextFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	ServletRequestAttributes attributes = new ServletRequestAttributes(request, response);
	initContextHolders(request, attributes);

	try {
		filterChain.doFilter(request, response);
	}
	finally {
		resetContextHolders();
		if (logger.isTraceEnabled()) {
			logger.trace("Cleared thread-bound request context: " + request);
		}
		attributes.requestCompleted();
	}
}
 
Example 2
Source File: ExampleFilter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
        throws IOException, ServletException {

    // Store ourselves as a request attribute (if requested)
    if (attribute != null)
        request.setAttribute(attribute, this);

    // Time and log the subsequent processing
    long startTime = System.currentTimeMillis();
    chain.doFilter(request, response);
    long stopTime = System.currentTimeMillis();
    filterConfig.getServletContext().log
        (this.toString() + ": " + (stopTime - startTime) +
         " milliseconds");
}
 
Example 3
Source File: JwtAuthenticationTokenFilter.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 4
Source File: AdminLoginFilter.java    From Movie-Ticketing-System-BC-2018.7 with MIT License 6 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain chain) throws ServletException, IOException {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpSession session = req.getSession();
    
    String requestURI = req.getRequestURI();
    String uri = requestURI.substring(requestURI.indexOf(LOGIN_PREFIX));
    if (uri.indexOf(LOGIN_KEYWORD) == -1) {
        Admin admin = (Admin)session.getAttribute(ATTR_ADMINUSER);
        if (admin == null) {
            String loginUri = ".." + LOGIN_PREFIX + LOGIN_PAGE;
            ((HttpServletResponse)response).sendRedirect(loginUri);
            return;               
        }
    }
    
    chain.doFilter(request, response);
}
 
Example 5
Source File: RecentlyAccessedFilter.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    Optional<String> currentGroup = getCurrentRequestGroup(request);
    if (currentGroup.isPresent()) {
        logger.debug("recent groups filter, uri:{}, group:{}", request.getRequestURI(), currentGroup.get());
        Cookie[] cookies = request.getCookies();
        List<String> recentGroups = new ArrayList<>();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (COOKIE_KEY_RECENTLY_ACCESSED_GROUPS.equals(cookie.getName())) {
                    recentGroups = decodeRecentlyAccessedGroups(cookie.getValue());
                    break;
                }
            }
        }
        List<String> updatedRecentGroups = updateRecentGroups(recentGroups, currentGroup.get());
        String encodedCookie = BaseEncoding.base64Url().omitPadding().encode(JOINER.join(updatedRecentGroups).getBytes(Charsets.UTF_8));
        Cookie updatedCookie = new Cookie(COOKIE_KEY_RECENTLY_ACCESSED_GROUPS, encodedCookie);
        updatedCookie.setPath(COOKIE_PATH);
        response.addCookie(updatedCookie);
    }
    chain.doFilter(servletRequest, servletResponse);
}
 
Example 6
Source File: CaptchaAuthenticationFilter.java    From cola with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;

	AuthenticationFailureHandler authenticationFailureHandler = requiresAuthentication(request, response);
	if (authenticationFailureHandler == null) {
		chain.doFilter(request, response);
		return;
	}

	Object captcha = request.getSession().getAttribute(LOGIN_CAPTCHA_SESSION_KEY);

	if (captcha == null) {
		chain.doFilter(request, response);
	} else {
		if (!String.valueOf(captcha).equalsIgnoreCase(request.getParameter(LOGIN_CAPTCHA_PARAM_NAME))) {
			authenticationFailureHandler.onAuthenticationFailure(request, response, new InsufficientAuthenticationException("验证码错误"));
		} else {
			chain.doFilter(request, response);
		}
	}
}
 
Example 7
Source File: ValidateCodeFilter.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * do filter.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;
    String uri = HttpRequestTools.getUri(req);
    //is login
    if (LOGIN_URI.equalsIgnoreCase(uri) && LOGIN_METHOD.equalsIgnoreCase(req.getMethod())) {
        try {
            validateCode(req);
        } catch (NodeMgrException ex) {
            NodeMgrTools.responseRetCodeException(rsp, ex.getRetCode());
            return;
        } finally {
            //remove token
            tokenService.deleteToken(req.getHeader("token"), null);
        }
    }
    chain.doFilter(request, response);
}
 
Example 8
Source File: ForwardedHeaderFilterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private String sendRedirect(final String location) throws ServletException, IOException {
	Filter filter = new OncePerRequestFilter() {
		@Override
		protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
				FilterChain chain) throws IOException {

			res.sendRedirect(location);
		}
	};

	MockHttpServletResponse response = new MockHttpServletResponse();
	FilterChain filterChain = new MockFilterChain(mock(HttpServlet.class), this.filter, filter);
	filterChain.doFilter(request, response);

	return response.getRedirectedUrl();
}
 
Example 9
Source File: TokenFilter.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
   throws IOException, ServletException {
   HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
   String token = resolveToken(httpServletRequest);
   String requestRri = httpServletRequest.getRequestURI();
   // 验证 token 是否存在
   OnlineUser onlineUser = null;
   try {
      SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
      OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
      onlineUser = onlineUserService.getOne(properties.getOnlineKey() + token);
   } catch (ExpiredJwtException e) {
      log.error(e.getMessage());
   }
   if (onlineUser != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
      Authentication authentication = tokenProvider.getAuthentication(token);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
   } else {
      log.debug("no valid JWT token found, uri: {}", requestRri);
   }
   filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 10
Source File: TenantFilter.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws IOException, ServletException {
    try {
        //优先获取请求参数中的tenantId值
        String tenantId = request.getParameter(CommonConstant.TENANT_ID_PARAM);
        if (StrUtil.isEmpty(tenantId)) {
            tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
        }
        //保存租户id
        if (StrUtil.isNotEmpty(tenantId)) {
            TenantContextHolder.setTenant(tenantId);
        }

        filterChain.doFilter(request, response);
    } finally {
        TenantContextHolder.clear();
    }
}
 
Example 11
Source File: ValidateCodeFilter.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    if (StrUtil.equals("/authentication/form", request.getRequestURI()) && StringUtils.endsWithIgnoreCase(request.getMethod(), "POST")) {
        try {
            validateCodeService.validate(new ServletWebRequest(request));
        } catch (ValidateCodeException exception) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
            return;
        }
    }

    chain.doFilter(request, response);

}
 
Example 12
Source File: SeataXidFilter.java    From demo-seata-springcloud with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {
	String xid = RootContext.getXID();
	String restXid = request.getHeader(SeataConstant.XID_HEADER);
	boolean bind = false;
	if (StringUtils.isBlank(xid) && StringUtils.isNotBlank(restXid)) {
		RootContext.bind(restXid);
		bind = true;
		if (logger.isDebugEnabled()) {
			logger.debug("bind[" + restXid + "] to RootContext");
		}
	}
	try {
		filterChain.doFilter(request, response);
	} finally {
		if (bind) {
			String unbindXid = RootContext.unbind();
			if (logger.isDebugEnabled()) {
				logger.debug("unbind[" + unbindXid + "] from RootContext");
			}
			if (!restXid.equalsIgnoreCase(unbindXid)) {
				logger.warn("xid in change during http rest from " + restXid + " to " + unbindXid);
				if (unbindXid != null) {
					RootContext.bind(unbindXid);
					logger.warn("bind [" + unbindXid + "] back to RootContext");
				}
			}
		}
	}

}
 
Example 13
Source File: CommonTotalFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest sRequest = (HttpServletRequest)request;
    String target = FilterUtil.filterTarget(sRequest);
    target = WebCallbackManager.getUrlCleaner().clean(target);

    Entry entry = null;
    try {
        ContextUtil.enter(target);
        entry = SphU.entry(TOTAL_URL_REQUEST);
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse)response;
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException e2) {
        Tracer.trace(e2);
        throw e2;
    } catch (ServletException e3) {
        Tracer.trace(e3);
        throw e3;
    } catch (RuntimeException e4) {
        Tracer.trace(e4);
        throw e4;
    } finally {
        if (entry != null) {
            entry.exit();
        }
        ContextUtil.exit();
    }
}
 
Example 14
Source File: JWTFilter.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
    throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    String jwt = resolveToken(httpServletRequest);
    if (jwt != null && StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
        Authentication authentication = this.tokenProvider.getAuthentication(jwt);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 15
Source File: LangFilter.java    From mPass with Apache License 2.0 5 votes vote down vote up
/**
 * 接收前端多语言切换请求,无则不处理
 *
 * @param request
 * @param response
 * @param chain
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    //多语言信息获取
    String lang = request.getHeader(HEADER_LANG_CLIENT);
    if (LangUtil.isSuportEnabled()) {
        if (!StringUtils.isEmpty(lang)) {
            List<LangInfo> blankList = LangUtil.getSupportLangs();
            lang = lang.replace(NamingConstant.UNDERLINE, NamingConstant.STRIKE);
            boolean inList = false;
            if (!CollectionUtils.isEmpty(blankList)) {
                for (LangInfo info : blankList) {
                    if (info.getLangCode().equalsIgnoreCase(lang)) {
                        inList = true;
                        break;
                }
            }
            }
            if (inList) {
                //在白名单内,则使用该语言
                ThreadLocalUtil.setLocalVar(ResourceUtil.class.getName() + "_switch", lang);
                ResourceUtil.switchLocale(ResourceUtil.toLocale(lang));
            } else {
                log.warn("客户端发出'" + lang + "'语言的请求,目前系统不支持或不在配置列表内,故设定转为官方语言。");
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 16
Source File: RESTRequestParameterProcessingFilter.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        Authentication authResult) throws IOException, ServletException {
    super.successfulAuthentication(request, response, chain, authResult);
    // carry on with the request
    chain.doFilter(request, response);
}
 
Example 17
Source File: JwtSsoBasedAuthenticationFilter.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    log.debug("=== doFilterInternal  ===");

    String header = request.getHeader(HEADER_AUTHORIZATION);
    if (header == null || !header.startsWith(PREFIX_BEARER_TOKEN)) {
        chain.doFilter(request, response);
        return;
    }
    UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(request, response);
}
 
Example 18
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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 19
Source File: StandaloneMockMvcBuilderTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	filterChain.doFilter(request, response);
}
 
Example 20
Source File: StandardRequestWrappingFilter.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    chain.doFilter(new StandardRequestWrapper((HttpServletRequest) request), new StandardResponseWrapper((HttpServletResponse) response));
}