Search in sources :

Example 41 with HttpServletRequestWrapper

use of javax.servlet.http.HttpServletRequestWrapper in project hadoop by apache.

the class TestStaticUserWebFilter method testFilter.

@Test
public void testFilter() throws Exception {
    FilterConfig config = mockConfig("myuser");
    StaticUserFilter suf = new StaticUserFilter();
    suf.init(config);
    ArgumentCaptor<HttpServletRequestWrapper> wrapperArg = ArgumentCaptor.forClass(HttpServletRequestWrapper.class);
    FilterChain chain = mock(FilterChain.class);
    suf.doFilter(mock(HttpServletRequest.class), mock(ServletResponse.class), chain);
    Mockito.verify(chain).doFilter(wrapperArg.capture(), Mockito.<ServletResponse>anyObject());
    HttpServletRequestWrapper wrapper = wrapperArg.getValue();
    assertEquals("myuser", wrapper.getUserPrincipal().getName());
    assertEquals("myuser", wrapper.getRemoteUser());
    suf.destroy();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) FilterChain(javax.servlet.FilterChain) StaticUserFilter(org.apache.hadoop.http.lib.StaticUserWebFilter.StaticUserFilter) FilterConfig(javax.servlet.FilterConfig) Test(org.junit.Test)

Example 42 with HttpServletRequestWrapper

use of javax.servlet.http.HttpServletRequestWrapper in project hadoop by apache.

the class AuthenticationFilter method doFilter.

/**
   * 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.
   * @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) {
            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 != AuthenticationToken.ANONYMOUS) {
                    if (token.getMaxInactives() > 0) {
                        token.setMaxInactives(System.currentTimeMillis() + getMaxInactiveInterval() * 1000);
                    }
                    if (token.getExpires() != 0) {
                        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 the token is an old one, renew the its maxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getMaxInactiveInterval() > 0) {
                    token.setMaxInactives(System.currentTimeMillis() + getMaxInactiveInterval() * 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);
                }
                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("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(), isHttps);
            // 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());
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) Principal(java.security.Principal)

Example 43 with HttpServletRequestWrapper

use of javax.servlet.http.HttpServletRequestWrapper in project OpenAM by OpenRock.

the class AuthenticationServiceV1 method wrapRequest.

/**
     * Wraps the HttpServletRequest with the realm information used in the URI.
     *
     * @param request The HttpServletRequest.
     * @return The wrapped HttpServletRequest.
     */
private HttpServletRequest wrapRequest(final HttpServletRequest request, final RealmContext realmContext, final JsonValue jsonValue) {
    return new HttpServletRequestWrapper(request) {

        @Override
        public String getParameter(String name) {
            if (REALM.equals(name)) {
                return realmContext.getResolvedRealm();
            }
            if (JSONCONTENT.equals(name)) {
                return jsonValue.toString();
            }
            return super.getParameter(name);
        }

        @Override
        public Map getParameterMap() {
            Map params = super.getParameterMap();
            Map p = new HashMap(params);
            p.put(REALM, realmContext.getResolvedRealm());
            return p;
        }

        @Override
        public Enumeration getParameterNames() {
            Set<String> names = new HashSet<>();
            Enumeration<String> paramNames = super.getParameterNames();
            while (paramNames.hasMoreElements()) {
                names.add(paramNames.nextElement());
            }
            names.add(REALM);
            return Collections.enumeration(names);
        }

        @Override
        public String[] getParameterValues(String name) {
            if (REALM.equals(name)) {
                return new String[] { realmContext.getResolvedRealm() };
            }
            return super.getParameterValues(name);
        }
    };
}
Also used : HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 44 with HttpServletRequestWrapper

use of javax.servlet.http.HttpServletRequestWrapper in project atmosphere by Atmosphere.

the class AtmosphereRequestImpl method getHeader.

@Override
public String getHeader(String s, boolean checkCase) {
    if ("content-type".equalsIgnoreCase(s)) {
        return getContentType();
    }
    String name = b.request.getHeader(s);
    if (name == null) {
        if (b.headers.get(s) != null) {
            return b.headers.get(s);
        }
        if (s.startsWith(X_ATMOSPHERE) && isNotNoOps()) {
            // Craziness with Struts 2 who wraps String attribute as BigDecimal
            // https://github.com/Atmosphere/atmosphere/issues/1367
            Object o = attributeWithoutException(b.request, s);
            if (o == null || String.class.isAssignableFrom(o.getClass())) {
                name = String.class.cast(o);
            } else {
                try {
                    if (HttpServletRequestWrapper.class.isAssignableFrom(b.request.getClass())) {
                        HttpServletRequest hsr = HttpServletRequestWrapper.class.cast(b.request);
                        while (hsr instanceof HttpServletRequestWrapper) {
                            hsr = (HttpServletRequest) ((HttpServletRequestWrapper) hsr).getRequest();
                            o = attributeWithoutException(hsr, s);
                            if (o == null || String.class.isAssignableFrom(o.getClass())) {
                                name = String.class.cast(o);
                                break;
                            }
                        }
                    }
                } catch (Exception ex) {
                    logger.warn("", ex);
                }
            }
        }
    }
    if (name == null && checkCase) {
        return getHeader(s.toLowerCase(), false);
    }
    if (name == null && "connection".equalsIgnoreCase(s)) {
        return "keep-alive";
    }
    return name;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 45 with HttpServletRequestWrapper

use of javax.servlet.http.HttpServletRequestWrapper in project azure-tools-for-java by Microsoft.

the class SimpleAuthenticationHelper method clearSessionCoookie.

// this needs refactoring.
private HttpServletRequest clearSessionCoookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Token token, final State state) {
    if (httpRequest == null || httpResponse == null || token == null || state == null) {
        throw new PreconditionException("Required parameter is null");
    }
    final Cookie redisSessionCookie = getCookie(httpRequest, "SESSION");
    final Cookie javaSessionCookie = getCookie(httpRequest, "JSESSIONID");
    if (redisSessionCookie != null || javaSessionCookie != null) {
        if (token.getUserID().toString().equals(state.getUserID())) {
            if (redisSessionCookie != null && redisSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
            if (javaSessionCookie != null && javaSessionCookie.getValue().equals(state.getSessionName())) {
                return httpRequest;
            }
        }
        if (redisSessionCookie != null) {
            redisSessionCookie.setMaxAge(0);
            httpResponse.addCookie(redisSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        if (javaSessionCookie != null) {
            javaSessionCookie.setMaxAge(0);
            httpResponse.addCookie(javaSessionCookie);
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        return new HttpServletRequestWrapper(httpRequest) {

            @Override
            public Cookie[] getCookies() {
                final List<Cookie> cookieList = new ArrayList<Cookie>();
                for (Cookie cookie : httpRequest.getCookies()) {
                    if (!cookie.getName().equals("SESSION") && !cookie.getName().equals("JSESSIONID")) {
                        cookieList.add(cookie);
                    }
                }
                final Cookie[] cookieArray = new Cookie[cookieList.size()];
                cookieList.toArray(cookieArray);
                return cookieArray;
            }
        };
    }
    return httpRequest;
}
Also used : Cookie(javax.servlet.http.Cookie) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) PreconditionException(com.microsoft.azure.oidc.exception.PreconditionException)

Aggregations

HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)54 HttpServletRequest (javax.servlet.http.HttpServletRequest)42 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 ServletRequest (javax.servlet.ServletRequest)13 ServletResponse (javax.servlet.ServletResponse)11 IOException (java.io.IOException)10 FilterChain (javax.servlet.FilterChain)10 ServletException (javax.servlet.ServletException)9 Test (org.junit.Test)9 HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)8 FilterConfig (javax.servlet.FilterConfig)7 Principal (java.security.Principal)6 Filter (javax.servlet.Filter)6 ArrayList (java.util.ArrayList)5 Provider (com.google.inject.Provider)4 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)4 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)4 OutputStream (java.io.OutputStream)4 Cookie (javax.servlet.http.Cookie)4 Injector (com.google.inject.Injector)2