Example usage for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper

List of usage examples for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper.

Prototype

public HttpServletRequestWrapper(HttpServletRequest request) 

Source Link

Document

Constructs a request object wrapping the given request.

Usage

From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override//from   w  ww .jav  a 2s .  c  o m
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(ThreadLocalRandom.current().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity) {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request) throws AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, name, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps);
                            request.setAttribute(SIGNED_TOKEN_ATTRIBUTE,
                                    tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(),
                                            token.getExpires(), !token.isExpired() && token.getExpires() > 0,
                                            isHttps));
                        }
                        // Since this request is validated also set DRUID_AUTHENTICATION_RESULT
                        request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                                new AuthenticationResult(token.getName(), authorizerName, name, null));
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug(ex, "Authentication exception: " + ex.getMessage());
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:org.apache.felix.webconsole.internal.servlet.OsgiManager.java

private HttpServletRequest wrapRequest(final HttpServletRequest request, final Locale locale) {
    return new HttpServletRequestWrapper(request) {
        /**//from w  w  w.j av  a2s  . com
         * @see javax.servlet.ServletRequestWrapper#getLocale()
         */
        public Locale getLocale() {
            return locale;
        }
    };
}

From source file:org.apache.hadoop.security.authentication.server.AuthenticationFilter.java

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object.//from   ww w.ja  v  a  2 s  . c  om
 * @param response the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
        boolean newToken = false;
        AuthenticationToken token = getToken(httpRequest);
        if (token == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} triggering authentication",
                        getRequestURL(httpRequest)));
            }
            token = authHandler.authenticate(httpRequest, httpResponse);
            if (token != null && token != AuthenticationToken.ANONYMOUS) {
                token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
            }
            newToken = true;
        }
        if (token != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} user {1} authenticated", getRequestURL(httpRequest),
                        token.getUserName()));
            }
            final AuthenticationToken authToken = token;
            httpRequest = new HttpServletRequestWrapper(httpRequest) {
                @Override
                public String getAuthType() {
                    return authToken.getType();
                }

                @Override
                public String getRemoteUser() {
                    return authToken.getUserName();
                }

                @Override
                public Principal getUserPrincipal() {
                    return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                }
            };
            if (newToken && token != AuthenticationToken.ANONYMOUS) {
                String signedToken = signer.sign(token.toString());
                Cookie cookie = createCookie(signedToken);
                httpResponse.addCookie(cookie);
            }
            filterChain.doFilter(httpRequest, httpResponse);
        }
    } catch (AuthenticationException ex) {
        if (!httpResponse.isCommitted()) {
            Cookie cookie = createCookie("");
            cookie.setMaxAge(0);
            httpResponse.addCookie(cookie);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        }
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKrbFilter.java

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object.//from www .  ja  v a  2s  .  c o  m
 * @param response the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            ex.printStackTrace();
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        ex.printStackTrace();
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM,
                        RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
                if (agents == null) {
                    agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT;
                }
                parseBrowserUserAgents(agents);
                if (isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT))) {
                    ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, "");
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie")
                                && value.startsWith("RANGERADMINSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.apache.solr.security.BasicAuthPlugin.java

@Override
public boolean doAuthenticate(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws Exception {

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

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        BasicAuthPlugin.authHeader.set(new BasicHeader("Authorization", authHeader));
        StringTokenizer st = new StringTokenizer(authHeader);
        if (st.hasMoreTokens()) {
            String basic = st.nextToken();
            if (basic.equalsIgnoreCase("Basic")) {
                try {
                    String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                    int p = credentials.indexOf(":");
                    if (p != -1) {
                        final String username = credentials.substring(0, p).trim();
                        String pwd = credentials.substring(p + 1).trim();
                        if (!authenticate(username, pwd)) {
                            log.debug("Bad auth credentials supplied in Authorization header");
                            authenticationFailure(response, "Bad credentials");
                        } else {
                            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                                @Override
                                public Principal getUserPrincipal() {
                                    return new BasicUserPrincipal(username);
                                }//from w w w  .  j a  v  a  2  s.c  om
                            };
                            filterChain.doFilter(wrapper, response);
                            return true;
                        }

                    } else {
                        authenticationFailure(response, "Invalid authentication token");
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new Error("Couldn't retrieve authentication", e);
                }
            }
        }
    } else {
        if (blockUnknown) {
            authenticationFailure(response, "require authentication");
        } else {
            request.setAttribute(AuthenticationPlugin.class.getName(),
                    authenticationProvider.getPromptHeaders());
            filterChain.doFilter(request, response);
            return true;
        }
    }
    return false;
}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * If the request has a valid authentication token it allows the request to continue to
 * the target resource,// ww  w.j ava 2s.com
 * otherwise it triggers a GSS-API sequence for authentication
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got token {} from httpRequest {}", token, getRequestURL(httpRequest));
                if (null != token) {
                    LOG.debug("token.isExpired() = " + token.isExpired());
                }
            }
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            if (!ex.getMessage().equals("Empty token")) {
                // will be sent back in a 401 unless filter authenticates
                authenticationEx = ex;
            }
            token = null;
        }
        if (managementOperation(token, httpRequest, httpResponse)) {
            if (token == null || token.isExpired()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication. handler: {}", getRequestURL(httpRequest),
                            this.getClass());
                }
                token = authenticate(httpRequest, httpResponse);
                if (token != null && token != AuthenticationToken.ANONYMOUS) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            if (token.getMaxInactives() > 0) {
                    //              token.setMaxInactives(System.currentTimeMillis()
                    //                  + getTokenMaxInactiveInterval() * 1000);
                    //            }
                    if (token.getExpires() != 0) {
                        token.setExpires(System.currentTimeMillis() + getTokenValidity() * 1000);
                    }
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };

                // If cookie persistence is configured to false,
                // it means the cookie will be a session cookie.
                // If the token is an old one, renew the its tokenMaxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getTokenMaxInactiveInterval() > 0) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            token.setMaxInactives(System.currentTimeMillis()
                    //                + getTokenMaxInactiveInterval() * 1000);
                    token.setExpires(token.getExpires());
                    newToken = true;
                }
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isCookiePersistent(), isHttps);
                }
                KerberosToken kerberosToken = new KerberosToken(token.getUserName(), token.toString());
                SecurityUtils.getSubject().login(kerberosToken);
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("managementOperation returned false for request {}." + " token: {}",
                        getRequestURL(httpRequest), token);
            }
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(),
                    isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                httpResponse.sendError(errCode, "Authentication required");
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.apereo.portal.spring.security.RemoteUserSettingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final String remoteUser = StringUtils.trimToNull(FileUtils.readFileToString(this.remoteUserFile));

    if (remoteUser != null) {
        request = new HttpServletRequestWrapper((HttpServletRequest) request) {
            /* (non-Javadoc)
             * @see javax.servlet.http.HttpServletRequestWrapper#getRemoteUser()
             *//*from ww  w . j av a2  s . c  om*/
            @Override
            public String getRemoteUser() {
                return remoteUser;
            }

            /* (non-Javadoc)
             * @see javax.servlet.http.HttpServletRequestWrapper#getHeader(java.lang.String)
             */
            @Override
            public String getHeader(String name) {
                if ("REMOTE_USER".equals(name)) {
                    return remoteUser;
                }
                return super.getHeader(name);
            }

            /* (non-Javadoc)
             * @see javax.servlet.http.HttpServletRequestWrapper#getHeaders(java.lang.String)
             */
            @Override
            public Enumeration<String> getHeaders(String name) {
                if ("REMOTE_USER".equals(name)) {
                    return Iterators.asEnumeration(Collections.singleton(remoteUser).iterator());
                }
                return super.getHeaders(name);
            }

            /* (non-Javadoc)
             * @see javax.servlet.http.HttpServletRequestWrapper#getHeaderNames()
             */
            @Override
            public Enumeration<String> getHeaderNames() {
                final LinkedHashSet<String> headers = new LinkedHashSet<String>();
                for (final Enumeration<String> headersEnum = super.getHeaderNames(); headersEnum
                        .hasMoreElements();) {
                    headers.add(headersEnum.nextElement());
                }
                headers.add("REMOTE_USER");

                return Iterators.asEnumeration(headers.iterator());
            }

            /* (non-Javadoc)
             * @see javax.servlet.http.HttpServletRequestWrapper#getIntHeader(java.lang.String)
             */
            @Override
            public int getIntHeader(String name) {
                if ("REMOTE_USER".equals(name)) {
                    return Integer.valueOf(remoteUser);
                }
                return super.getIntHeader(name);
            }
        };
    }

    chain.doFilter(request, response);
}

From source file:org.artificer.server.filters.MavenRepositoryAuthFilter.java

/**
 * Wrap/proxy the http request.// w ww .  j  a  v  a 2s  .c  om
 * @param request
 * @param principal
 */
private HttpServletRequest wrapRequest(final ServletRequest request, final SimplePrincipal principal) {
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {
        @Override
        public Principal getUserPrincipal() {
            return principal;
        }

        @Override
        public String getRemoteUser() {
            return principal.getName();
        }

        /**
         * @see javax.servlet.http.HttpServletRequestWrapper#isUserInRole(java.lang.String)
         */
        @Override
        public boolean isUserInRole(String role) {
            return principal.getRoles().contains(role);
        }
    };
    return wrapper;
}

From source file:org.atomserver.server.servlet.BlockingFilter.java

private ServletRequest wrapServletRequest(ServletRequest servletRequest) throws IOException {
    final ServletInputStream originalInputStream = servletRequest.getInputStream();
    final int maxBytes = settings.getMaxContentLength();
    final ServletInputStream inputStream = new ServletInputStream() {
        int bytesRead = 0;

        public int read() throws IOException {
            if (bytesRead++ > maxBytes) {
                throw new TooMuchDataException("Content length exceeds the maximum length allowed.");
            }/*from   w  w  w  .ja  va2 s.c  o  m*/
            return originalInputStream.read();
        }
    };
    // wrap the original request, returning the wrapped input stream instead
    return new HttpServletRequestWrapper((HttpServletRequest) servletRequest) {
        public ServletInputStream getInputStream() throws IOException {
            return inputStream;
        }
    };
}

From source file:org.broadleafcommerce.openadmin.web.filter.BroadleafAdminTypedEntityRequestFilter.java

@SuppressWarnings("unchecked")
public boolean isRequestForTypedEntity(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    String servletPath = request.getServletPath();
    if (!servletPath.contains(":")) {
        return false;
    }// w  w  w. j  a  v  a 2 s .  c o m

    // Find the Admin Section for the typed entity.
    String sectionKey = getSectionKeyFromRequest(request);
    AdminSection typedEntitySection = adminNavigationService.findAdminSectionByURI(sectionKey);

    // If the Typed Entity Section does not exist, continue with the filter chain.
    if (typedEntitySection == null) {
        return false;
    }

    // Check if admin user has access to this section.
    if (!adminUserHasAccess(typedEntitySection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access is denied");
        return true;
    }

    // Add the typed entity admin section to the request.
    request.setAttribute("typedEntitySection", typedEntitySection);

    // Find the type and build the new path.
    String type = getEntityTypeFromRequest(request);
    final String forwardPath = servletPath.replace(type, "");

    // Get the type field name on the Entity for the given section.
    String typedFieldName = getTypeFieldName(typedEntitySection);

    // Build out the new parameter map to be forwarded.
    final Map parameters = new LinkedHashMap(request.getParameterMap());
    if (typedFieldName != null) {
        parameters.put(typedFieldName, new String[] { type.substring(1).toUpperCase() });
    }

    // Build our request wrapper.
    final HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
        @Override
        public String getParameter(String name) {
            Object temp = parameters.get(name);
            Object[] response = new Object[0];
            if (temp != null) {
                ArrayUtils.addAll(response, temp);
            }
            if (ArrayUtils.isEmpty(response)) {
                return null;
            } else {
                return (String) response[0];
            }
        }

        @Override
        public Map getParameterMap() {
            return parameters;
        }

        @Override
        public Enumeration getParameterNames() {
            return new IteratorEnumeration(parameters.keySet().iterator());
        }

        @Override
        public String[] getParameterValues(String name) {
            return (String[]) parameters.get(name);
        }

        @Override
        public String getServletPath() {
            return forwardPath;
        }
    };
    requestProcessor.process(new ServletWebRequest(wrapper, response));

    // Forward the wrapper to the appropriate path
    wrapper.getRequestDispatcher(wrapper.getServletPath()).forward(wrapper, response);
    return true;
}