Example usage for javax.servlet.http Cookie getName

List of usage examples for javax.servlet.http Cookie getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*w  w  w. j  a  v  a 2 s.c om*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:ch.entwine.weblounge.common.impl.request.RequestUtils.java

/**
 * Returns <code>true</code> if the editing state is enabled, else return
 * <code>false</code>/*w ww  . j ava2 s . co m*/
 * 
 * @param request
 *          the request
 * @return the editing state
 */
public static boolean isEditingState(WebloungeRequest request) {
    if (request.getHeader("X-Weblounge-Special") != null) {
        return "Page-Preview".equals(request.getHeader("X-Weblounge-Special"));
    } else if (!SecurityUtils.userHasRole(request.getUser(), EDITOR)) {
        return false;
    } else if (request.getParameter(WORKBENCH_PREVIEW_PARAM) != null) {
        return false;
    } else if (request.getParameter(WORKBENCH_PARAM) != null) {
        return true;
    } else if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            if (EditingState.STATE_COOKIE.equals(cookie.getName())) {
                return true;
            }
        }
    } else if (TRUE.equals(request.getSession().getAttribute(STATE_COOKIE))) {
        return true;
    }

    return false;
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

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

        @Override//from   w w w  .jav  a 2  s .c  om
        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(new Random().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)
                            throws Exception {

                    }

                    @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 IOException, 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, 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());
                            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
                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, 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:CookieReader.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean hasCookies = false;

    if (cookies != null)
        hasCookies = true;/*from w w  w .  j  av  a2 s.c  o  m*/

    // display the name/value of each cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie information</title>");
    out.println("</head>");
    out.println("<body>");
    if (hasCookies) {
        out.println("<h2> The name and value of each found cookie</h2>");
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.println("Name of cookie #" + (i + 1) + ": " + cookie.getName() + "<br>");
            out.println("Value of cookie #" + (i + 1) + ": " + cookie.getValue() + "<br><br>");

        }
    } else {
        out.println("<h2> This request did not include any cookies</h2>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean hasCookies = false;

    if (cookies != null)
        hasCookies = true;/*from  w w w. j  a  va2 s.com*/

    // display the name/value of each cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie information</title>");
    out.println("</head>");
    out.println("<body>");
    if (hasCookies) {
        out.println("<h2> The name and value of each found cookie</h2>");

        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.println("Name of cookie #" + (i + 1) + ": " + cookie.getName() + "<br>");
            out.println("Value of cookie #" + (i + 1) + ": " + cookie.getValue() + "<br><br>");

        }

    } else {
        out.println("<h2> This request did not include any cookies</h2>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

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

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

        @Override//from ww w . j av  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:de.innovationgate.wga.server.api.Call.java

/**
 * Removes a cookie from the call, so it will be deleted on the client.
 * @param c The cookie to delete.//from   w w  w  .j  ava  2s  . c o  m
 * @throws WGException
 */
public void removeCookie(Cookie c) throws WGException {
    testResponseHeaderWritable();
    if (!c.isFromClient()) {
        throw new WGAServerException("The cookie does not originate from the client and cannot be removed");
    }
    c.setMaxAge(0);
    getJavaResponse().addCookie(c.toJavaCookie());
    fetchCookies().remove(c.getName());
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//from ww  w . j  a va 2 s . c  om
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java

/**
 * Cookie?????.//from  ww  w.  ja  v a 2  s . co  m
 * @param key
 *            ??
 * @return ?. ???null
 */
public String getCookieValue(String key) {
    String value = null;
    Cookie[] cookies = ((HttpServletRequest) getExternalContext().getRequest()).getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName() != null && cookie.getName().equals(key)) {
                value = cookie.getValue();
            }
        }
    }
    return value;
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

private void copyRequestHeaders(final HttpServletRequest request, final ClientHttpRequest forwardRequest) {
    // Copy all the headers (necessary for ACCEPT and security headers especially). Do not copy the cookie header.
    final HttpHeaders headers = forwardRequest.getHeaders();
    final Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            if (!NAME_HEADER_COOKIE.equals(headerName)) {
                final String headerValue = request.getHeader(headerName);
                log.debug("Request Header: name = {} value = {}", headerName, headerValue);
                headers.add(headerName, headerValue);
            }//  w  w w.ja  va 2s. c  o m
        }
    }
    // Lets add the cookie as an header
    final Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        StringBuilder builder = null;
        for (final Cookie cookie : request.getCookies()) {
            if (builder == null) {
                builder = new StringBuilder();
            } else {
                builder.append(",");
            }
            builder.append(cookie.getName()).append("=").append(cookie.getValue());
        }
        if (builder != null) {
            final String cookieValue = builder.toString();
            headers.add(NAME_HEADER_COOKIE, cookieValue);
            log.debug("Request Header: name = {} value = {}", NAME_HEADER_COOKIE, cookieValue);
        }
    }
    // This method only called when need to forward so add the forwarded from header
    headers.add(JobConstants.GENIE_FORWARDED_FROM_HEADER, request.getRequestURL().toString());
}