Example usage for javax.servlet FilterChain doFilter

List of usage examples for javax.servlet FilterChain doFilter

Introduction

In this page you can find the example usage for javax.servlet FilterChain doFilter.

Prototype

public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException;

Source Link

Document

Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

Usage

From source file:edu.zipcloud.cloudstreetmarket.core.authentication.CustomOAuth2RequestFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    final boolean debug = logger.isDebugEnabled();

    String userIdentifier = request.getHeader(SPI_HEADER);

    if (userIdentifier == null) {
        chain.doFilter(request, response);
        return;//ww  w .  ja  va 2  s  .  co m
    }

    try {
        SocialUser socialUser = getRegisteredUser(userIdentifier);
        if (socialUser == null) {
            response.setHeader(MUST_REGISTER_HEADER, request.getHeader(SPI_HEADER));
            chain.doFilter(request, response);
            return;
        }

        if (authenticationIsRequired(socialUser.getUserId())) {
            User registeredUser = communityService.findOne(socialUser.getUserId());

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    registeredUser, registeredUser.getPassword(), registeredUser.getAuthorities());
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);
            rememberMeServices.loginSuccess(request, response, authResult);
            onSuccessfulAuthentication(request, response, authResult);
        }

    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }

        rememberMeServices.loginFail(request, response);

        onUnsuccessfulAuthentication(request, response, failed);

        if (ignoreFailure) {
            chain.doFilter(request, response);
        }
        return;
    }

    chain.doFilter(request, response);
}

From source file:com.hillert.botanic.filter.SimpleCorsFilter.java

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", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
    chain.doFilter(req, res);
}

From source file:org.ovirt.engine.api.common.security.CSRFProtectionFilter.java

private void doFilterExistingSession(HttpSession session, HttpServletRequest request,
        HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Check if the protection is enabled for this session, if it isn't then jump to the next filter:
    boolean enabled = (Boolean) session.getAttribute(ENABLED_ATTRIBUTE);
    if (!enabled) {
        chain.doFilter(request, response);
        return;/*from   w w w  . j a v a  2 s  .  c  om*/
    }

    // Check if the request contains a session id header, if it doesn't then it must be rejected immediately:
    String sessionIdHeader = request.getHeader(SESSION_ID_HEADER);
    if (sessionIdHeader == null) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the the session id header \"{}\" hasn't been provided.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Check if the actual session id matches the session id header:
    String actualSessionId = session.getId();
    if (!sessionIdHeader.equals(actualSessionId)) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the value of the session id header \"{}\" doesn't match the actual session "
                        + "id.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Everything is OK, let the request go to the next filter:
    chain.doFilter(request, response);
}

From source file:com.nitsoft.ecommerce.CorsFilter.java

@Override
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", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");
    chain.doFilter(req, res);
}

From source file:nu.yona.server.rest.LocalizationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    request = new LocalizationRequestWrapper(properties, request);
    response.setHeader(HttpHeaders.CONTENT_LANGUAGE, Translator.getStandardLocaleString(request.getLocale()));

    chain.doFilter(request, response);
}

From source file:com.nguyenle.tellme.travel.webservice.controller.TellmeTravelCORSFilter.java

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", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
    chain.doFilter(req, res);
}

From source file:io.apiman.common.servlet.AuthenticationFilter.java

/**
 * Further process the filter chain.//from  w w  w.  j a  v a 2s.c om
 * @param request
 * @param response
 * @param chain
 * @param principal
 * @throws IOException
 * @throws ServletException
 */
protected void doFilterChain(ServletRequest request, ServletResponse response, FilterChain chain,
        AuthPrincipal principal) throws IOException, ServletException {
    if (principal == null) {
        chain.doFilter(request, response);
    } else {
        HttpServletRequest hsr = null;
        hsr = wrapTheRequest(request, principal);
        chain.doFilter(hsr, response);
    }
}

From source file:org.unitec.maven.FiltroCorsSimple.java

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", "POST,GET,PUT" + "OPTION,DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
    chain.doFilter(req, res);

}

From source file:de.xwic.sandbox.security.SSOAuthFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (!enabled) {
        // do not do any SSO authentication if disabled.
        chain.doFilter(request, response);
        return;//from   ww  w.ja  v  a2s  .  c o m
    }

    // is session authenticated?
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        if (session.getAttribute(SessionRequestFilter.USER_SESSION_KEY) != null) {
            // user is authenticated -> pass through
            chain.doFilter(request, response);

        } else {
            // user is not yet authenticated ... try to detect via cookie
            IUser detectedUser = DAOSystem.getSecurityManager().detectUser();
            if (detectedUser != null) {
                // user was detected via cookie -> pass through
                log.debug("User '" + detectedUser.getName()
                        + "' successfully detected through cookie (remote host: " + req.getRemoteAddr() + ")");

                handleAlternativeUser(req, detectedUser.getLogonName());

                //SystemAccessLogger.logLogon(req.getRemoteAddr(), "Auth via Cookie");
                chain.doFilter(request, res);

            } else {

                // on localhost access can be passed through via syslogon command.
                if (req.getParameter("syslogon") != null && "127.0.0.1".equals(req.getRemoteAddr())) {
                    log.info("SYSLOGON requested.");
                    session.setAttribute("SYSLOGON_OVERRIDE", true);
                    chain.doFilter(req, res);
                    return;
                } else if (session.getAttribute("SYSLOGON_OVERRIDE") != null) {
                    chain.doFilter(req, res);
                    return;
                }

                // need to do SSO authentication process
                if (session.getAttribute(SSOHandler.SESSION_KEY_REQ_TOKEN) != null
                        && "1".equals(req.getParameter("_auth"))) {

                    String username = ssoHandler.checkAuthentication(req, res);
                    if (username == null) {
                        // authentication failed. try again 1 more time.
                        if (session.getAttribute("AUTH_RETRY") != null) {
                            // fall through, using app based authentication...
                            log.info(
                                    "User not authenticated by SSO auth. Passing on to application based authentication.");
                            chain.doFilter(req, res);
                        } else {
                            log.debug("Retrying authentication process ...");
                            session.setAttribute("AUTH_RETRY", "1");
                            ssoHandler.startAuthentication(req, res);
                        }
                    } else {

                        // logon successfull -> remove default domain (if set)
                        if (baseDomain != null
                                && username.toUpperCase().startsWith(baseDomain.toUpperCase() + "\\")) {
                            username = username.substring(baseDomain.length() + 1);
                        }
                        log.debug("Logon successfull. Detected user: " + username);
                        IUser user = ServerSecurityManager.getInstance().findUser(username);
                        if (user == null) {
                            //SystemAccessLogger.logLogonFailed(req.getRemoteAddr(), "User is unknown: " + username);
                            res.sendRedirect("unknownuser.html");
                            req.getSession().invalidate();
                        } else {

                            SessionRequestFilter.getSession()
                                    .setAttribute(SessionRequestFilter.USER_SESSION_KEY, username);
                            ServerSecurityManager.setCurrentUser(username);

                            handleAlternativeUser(req, username);

                            // check rights
                            if (!DAOSystem.getSecurityManager().hasRight(IMitarbeiter.class.getName(),
                                    ISecurityManager.ACTION_READ)) {
                                res.sendRedirect("noaccess.html");
                                req.getSession().invalidate();
                            } else {

                                //SystemAccessLogger.logLogon(req.getRemoteAddr(), "Auth via SSO Plugin");
                                ServerSecurityManager.getInstance().rememberActiveUser(); // create cookie
                                chain.doFilter(req, res);

                            }

                        }
                    }

                } else {

                    // start the authentication process and do no longer forward the request.
                    log.debug("Starting authentication process...");
                    ssoHandler.startAuthentication(req, res);

                }

            }
        }

    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.cloudstone.emenu.web.filter.LicenceFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse resp = (HttpServletResponse) response;
    HttpServletRequest req = (HttpServletRequest) request;
    // add context before url
    // String context = req.getContextPath();
    String url = req.getRequestURI().toLowerCase();
    if (url.startsWith("/licence") || url.startsWith("/static")) {
        chain.doFilter(request, response);
        return;//from  w ww .ja va  2s.  com
    }
    // skip license check in non-prodution environment
    if (!Profiles.isProd()) {
        chain.doFilter(request, response);
        LOG.debug("not in production environment skip the license check");
        return;
    }
    if (licenceHelper.checkLicence().isSuccess()) {
        chain.doFilter(req, resp);
        return;
    }
    LOG.info("licence filter not pass");
    resp.sendRedirect("licence");
    return;
}