Example usage for javax.servlet ServletRequest getServletContext

List of usage examples for javax.servlet ServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:org.red5.logging.LoggerContextFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LoggerContext context = (LoggerContext) request.getServletContext()
            .getAttribute(Red5LoggerFactory.LOGGER_CONTEXT_ATTRIBUTE);
    // get the selector
    ContextSelector selector = Red5LoggerFactory.getContextSelector();
    if (context != null) {
        // set the thread local ref
        ((LoggingContextSelector) selector).setLocalContext(context);
    } else {/*from  w w w.  j a  va  2 s  .com*/
        System.err.printf("No context named %s was found%n", contextName);
    }
    chain.doFilter(request, response);
    // remove the thread local ref so that log contexts dont use the wrong contextName
    ((LoggingContextSelector) selector).removeLocalContext();
}

From source file:com.sonicle.webtop.core.app.shiro.filter.JWTSignatureVerifier.java

protected SecretKey getSigningKey(ServletRequest request) {
    //TODO: read the algo from a dedicated setting
    SignatureAlgorithm keyAlgorithm = SignatureAlgorithm.HS256;
    String secret = String.valueOf(request.getServletContext().getAttribute(SECRET_CONTEXT_ATTRIBUTE));
    return StringUtils.isBlank(secret) ? null
            : new SecretKeySpec(secret.getBytes(Charsets.UTF_8), keyAlgorithm.getJcaName());
}

From source file:com.medlog.webservice.lifecycle.Security.java

private void doBeforeProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
    if (debug) {/*from  www.  ja va2  s .  com*/

        log("context path: " + request.getServletContext().getContextPath());
        log("Security:DoBeforeProcessing");
    }

    // Write code here to process the request and/or response before
    // the rest of the filter chain is invoked.
    // For example, a logging filter might log items on the request object,
    // such as the parameters.
    /*
    * for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
    * String name = (String)en.nextElement();
    * String values[] = request.getParameterValues(name);
    * int n = values.length;
    * StringBuffer buf = new StringBuffer();
    * buf.append(name);
    * buf.append("=");
    * for(int i=0; i < n; i++) {
    * buf.append(values[i]);
    * if (i < n-1)
    * buf.append(",");
    * }
    * log(buf.toString());
    * }
     */
}

From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java

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

    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);

    logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr());

    if (httpReq.getSession(false) == null) {
        chain.doFilter(request, response);
        return;/*from   www. j  a va2 s.  c o m*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {

        logger.error("doFilter", e);
    }

    // Check the user session for the salt cache, if none is present we
    // create one
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache == null) {
        if (tokenTimeout == -1) {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build();
        } else {
            csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000)
                    .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build();
        }

        httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache);

        String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom());
        httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt);
    }

    // Generate the salt and store it in the users cache
    String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom());

    String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);
    SecurityInfo si = new SecurityInfo(saltNameAttr, salt);

    if (SecurityTokenFilter.checkReferer) {
        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
        logger.debug("doFilter: refHeader=" + refHeader);
        if (StringUtils.isNotBlank(refHeader)) {
            try {
                URL refUrl = new URL(refHeader);
                refHeader = refUrl.getHost();
            } catch (MalformedURLException mex) {
                logger.debug("doFilter: parsing referer header failed", mex);
            }
        }

        si.setRefererHost(refHeader);
    }

    logger.debug("doFilter: si=" + si.toString());

    csrfPreventionSaltCache.put(si, si);

    // Add the salt to the current request so it can be used
    // by the page rendered in this request
    httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si);

    // set CSRF cookie
    HttpSession session = httpReq.getSession(false);
    if (session != null && StringUtils.isNotBlank(csrfCookieName)) {

        if (logger.isDebugEnabled()) {
            Cookie[] cookies = httpReq.getCookies();
            // boolean cookiePresent = false;
            for (Cookie c : cookies) {
                String name = c.getName();
                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());
                // if (csrfCookieName.equals(name)) {
                // cookiePresent = true;
                // break;
                // }
            }
        }
        // if (!cookiePresent) {
        byte[] hashSalt = new byte[32];
        SecureRandom sr = new SecureRandom();
        sr.nextBytes(hashSalt);

        String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr);

        Cookie c = new Cookie(csrfCookieName, csrfHash);
        c.setMaxAge(1800);
        c.setSecure(false);
        c.setPath(httpReq.getContextPath());
        c.setHttpOnly(false);
        httpRes.addCookie(c);
        // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM,
        // hashStr);
        // }
    }

    chain.doFilter(request, response);
}

From source file:com.raissi.utils.CustomFileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    if (bypass) {
        filterChain.doFilter(request, response);
        return;//  ww  w.j  av  a 2s.co m
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);

    if (isMultipart) {
        logger.debug("Parsing file upload request");

        FileCleaningTracker fileCleaningTracker = FileCleanerCleanup
                .getFileCleaningTracker(request.getServletContext());
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
        if (thresholdSize != null) {
            diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
        }
        if (uploadDir != null) {
            diskFileItemFactory.setRepository(new File(uploadDir));
        }

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);

        logger.debug(
                "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");

        filterChain.doFilter(multipartRequest, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:cz.muni.fi.dndtroopsweb.security.ProtectFilter2.java

/**
 * Provides authentication for hero part of project - as specified in class
 * annotation Checks whether the user exists, if the password is matching
 * /*ww w.j av  a2s .  co m*/
 */
@Override
public void doFilter(ServletRequest r, ServletResponse s, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) r;
    HttpServletResponse response = (HttpServletResponse) s;

    String auth = request.getHeader("Authorization");
    if (auth == null) {
        response401(response);
        return;
    }
    String[] creds = parseAuthHeader(auth);
    String logname = creds[0];
    String password = creds[1];

    //get Spring context and UserFacade from it
    UserFacade userFacade = WebApplicationContextUtils.getWebApplicationContext(r.getServletContext())
            .getBean(UserFacade.class);
    UserDTO matchingUser = userFacade.findUserByName(logname);
    if (matchingUser == null) {
        log.warn("no user with name {}", logname);
        response401(response);
        return;
    }
    UserAuthDTO userAuthDTO = new UserAuthDTO();
    userAuthDTO.setUserId(matchingUser.getId());
    userAuthDTO.setPassword(password);

    if (!userFacade.authenticate(userAuthDTO)) {
        log.warn("wrong credentials: user={} password={}", creds[0], creds[1]);
        response401(response);
        return;
    }
    request.setAttribute("authenticatedUser", matchingUser);
    chain.doFilter(request, response);
}

From source file:com.netsteadfast.greenstep.base.filter.WebLoginCheckFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String redirectUrl = filterConfig.getInitParameter("redirectUrl");
    if (StringUtils.isBlank(redirectUrl)) {
        redirectUrl = "/pages/system/login_again.jsp";
    }//from   w w w.  j  av a2 s  .  c  om
    Object accountObj = httpRequest.getSession().getAttribute(Constants.SESS_ACCOUNT);
    if (accountObj == null || !(accountObj instanceof AccountObj)) {
        httpResponse.sendRedirect(request.getServletContext().getContextPath() + redirectUrl);
        return;
    }
    if (!this.isLogin(httpRequest, (AccountObj) accountObj)) {
        return;
    }
    chain.doFilter(request, response);
}

From source file:cz.muni.fi.dndtroopsweb.security.ProtectFilter.java

/**
 * Provides authentication for troop part of project - as specified in class
 * annotation Checks whether the user exists, if the password is matching
 * and if the user is admin and is allowed to access this part of the app
 *///from w w  w  . ja v a2s.co m
@Override
public void doFilter(ServletRequest r, ServletResponse s, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) r;
    HttpServletResponse response = (HttpServletResponse) s;

    String auth = request.getHeader("Authorization");
    if (auth == null) {
        response401(response);
        return;
    }
    String[] creds = parseAuthHeader(auth);
    String logname = creds[0];
    String password = creds[1];

    //get Spring context and UserFacade from it
    UserFacade userFacade = WebApplicationContextUtils.getWebApplicationContext(r.getServletContext())
            .getBean(UserFacade.class);
    UserDTO matchingUser = userFacade.findUserByName(logname);
    if (matchingUser == null) {
        log.warn("no user with name {}", logname);
        response401(response);
        return;
    }
    UserAuthDTO userAuthDTO = new UserAuthDTO();
    userAuthDTO.setUserId(matchingUser.getId());
    userAuthDTO.setPassword(password);
    if (!userFacade.isAdmin(matchingUser)) {
        log.warn("user not admin {}", matchingUser);
        response401(response);
        return;
    }
    if (!userFacade.authenticate(userAuthDTO)) {
        log.warn("wrong credentials: user={} password={}", creds[0], creds[1]);
        response401(response);
        return;
    }
    request.setAttribute("authenticatedUser", matchingUser);
    chain.doFilter(request, response);
}

From source file:com.versatus.jwebshield.filter.SessionCheckFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */// ww  w .j a v a 2s.  c om
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpRes = (HttpServletResponse) response;
    String reqInfo = "J-WebShield Alert: Session check failed! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: RequestURL=" + httpReq.getRequestURL().toString());

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.SESSION_CHECK_URL_EXCL_LIST_ATTR_NAME);

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            logger.info("doFilter: request (" + httpReq.getRequestURL().toString()
                    + " matches exclusion pattern, skipping session check");
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }

    HttpSession session = httpReq.getSession(false);
    logger.debug("doFilter: session=" + session);
    logger.debug("doFilter: session attr. " + attributeToCheck + "="
            + (session != null ? session.getAttribute(attributeToCheck) : ""));

    if (session == null || session.getAttribute(attributeToCheck) == null) {
        if (send401) {
            // TODO this is not working for regular requests, only for WS
            // calls
            httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            logger.info(reqInfo + " redirecting to " + redirectPage);

            RequestDispatcher rd = httpReq.getRequestDispatcher(redirectPage);
            if (rd != null) {
                rd.forward(request, response);
            }
            return;
        }

    }

    logger.info("doFilter: session check complete");

    // pass the request along the filter chain
    chain.doFilter(request, response);
}