Example usage for javax.servlet.http Cookie getSecure

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

Introduction

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

Prototype

public boolean getSecure() 

Source Link

Document

Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.

Usage

From source file:com.hypersocket.netty.HttpResponseServletWrapper.java

@Override
public void addCookie(Cookie cookie) {

    StringBuffer cookieHeader = new StringBuffer();

    cookieHeader.append(cookie.getName());
    cookieHeader.append("=");
    cookieHeader.append(cookie.getValue());
    if (cookie.getPath() != null) {
        cookieHeader.append("; Path=");
        cookieHeader.append(cookie.getPath());
    }//from  w  w  w.  ja  v  a2 s.  co m
    if (cookie.getDomain() != null) {
        cookieHeader.append("; Domain=");
        cookieHeader.append(cookie.getDomain());
    }
    if (cookie.getMaxAge() > 0) {
        cookieHeader.append("; Max-Age=");
        cookieHeader.append(cookie.getMaxAge());
        /**
         * This breaks IE when date of server and browser do not match
         */
        cookieHeader.append("; Expires=");
        if (cookie.getMaxAge() == 0) {
            cookieHeader.append(DateUtils.formatDate(new Date(10000), DateUtils.PATTERN_RFC1036));
        } else {
            cookieHeader.append(
                    DateUtils.formatDate(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L),
                            DateUtils.PATTERN_RFC1036));
        }
    }

    if (cookie.getSecure()) {
        cookieHeader.append("; Secure");
    }

    /**
     * Make sure we are not adding duplicate cookies
     */
    for (Entry<String, String> entry : response.getHeaders()) {
        if (entry.getKey().equals("Set-Cookie") && entry.getValue().equals(cookieHeader.toString())) {
            return;
        }
    }
    addHeader("Set-Cookie", cookieHeader.toString());

}

From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java

/**
 * This method simulates the authentication process against a content 
 * source, so that every document is consider here as public.
 * <p>//from   w w w.ja  v  a 2  s.co  m
 * Creates the authentication cookie and always return 200, unless there is 
 * any problem processing the request.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP No authentication start");

    //
    // Launch the authentication process
    //

    // Protection
    try {

        Cookie extAuthCookie = null;
        extAuthCookie = new Cookie("gsa_basic_noauth", "");

        extAuthCookie.setValue("true");

        String authCookieDomain = null;
        String authCookiePath = null;
        int authMaxAge = -1;

        // Cache cookie properties
        authCookieDomain = (request.getAttribute("authCookieDomain")).toString();
        authCookiePath = (request.getAttribute("authCookiePath")).toString();
        //authMaxAge
        try {
            authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
        } catch (NumberFormatException nfe) {
            logger.error(
                    "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
        }

        // Set extra cookie parameters
        extAuthCookie.setDomain(authCookieDomain);
        extAuthCookie.setPath(authCookiePath);
        extAuthCookie.setMaxAge(authMaxAge);

        // Log info
        if (logger.isDebugEnabled())
            logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":"
                    + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain()
                    + ":" + extAuthCookie.getSecure());

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP No Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) {
    List<Cookie> cookies = new ArrayList<Cookie>();
    for (javax.servlet.http.Cookie servletCookie : servletCookies) {
        Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue());
        if (servletCookie.getComment() != null) {
            cookieBuilder.setComment(servletCookie.getComment());
        }//from  w ww .j  a v  a  2s . c om
        if (servletCookie.getDomain() != null) {
            cookieBuilder.setDomain(servletCookie.getDomain());
        }
        if (servletCookie.getPath() != null) {
            cookieBuilder.setPath(servletCookie.getPath());
        }
        cookieBuilder.setMaxAge(servletCookie.getMaxAge());
        cookieBuilder.setVersion(servletCookie.getVersion());
        cookieBuilder.setSecured(servletCookie.getSecure());
        cookies.add(cookieBuilder.build());
    }
    return new Cookies(cookies);
}

From source file:ed.net.CookieJar.java

/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param destination the destination of the request
 * @param cookie {@link Cookie} to be matched
 * @return true if the cookie matches the criterium
 *//*from   w  w w . j ava2  s . co  m*/
private boolean match(URL destination, final Cookie cookie) {
    String host = destination.getHost();
    int port = destination.getPort();
    String path = destination.getPath();
    boolean secure = "https".equals(destination.getProtocol());

    if (host == null) {
        throw new IllegalArgumentException("Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException("Host of origin may not be blank");
    }
    if (port < 0) {
        port = 80;
    }
    if (path == null) {
        throw new IllegalArgumentException("Path of origin may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (path.trim().equals("")) {
        path = "/";
    }
    host = host.toLowerCase();
    if (cookie.getDomain() == null) {
        return false;
    }
    if (cookie.getPath() == null) {
        return false;
    }

    return
    // only add the cookie if it hasn't yet expired
    !isExpired(cookie)
            // and the domain pattern matches
            && (domainMatch(host, cookie.getDomain()))
            // and the path is null or matching
            && (pathMatch(path, cookie.getPath()))
            // and if the secure flag is set, only if the request is
            // actually secure
            && (cookie.getSecure() ? secure : true);
}

From source file:com.liferay.portal.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
        cookie.setDomain(domain);/* ww w  .  java2s .co  m*/
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java

/**
 * This is the main method that does the authentication and should be 
 * invoked by the classes that would like to open a new authentication 
 * process against an HTTP Basic protected source.
 * <p>/*from w w w  .  j a  v  a  2  s  . c  o  m*/
 * The username and password for the source are assumed to be the ones 
 * captured during the authentication. These are stored in creds and in 
 * this case the root parameters. creds is an array of credentials for 
 * all external sources. The first element is 'root' which contains the 
 * credentials captured from the login page. This method reviews if there 
 * is a credential id identical to the name associated to this module 
 * in the config file. If so, these credentials are used to authenticate 
 * against this HTTP Basic source, and if not 'root' one will be used 
 * instead.
 * <p>
 * If the HTTP Basic authentication result is OK, it creates an 
 * authentication cookie containing the HTTP Basic credentials 
 * to be reused during authorization. The content returned back from the 
 * remote secure backend system is sent as well. Anyway, the HTTP 
 * response code is returned in this method to inform the caller on the 
 * status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    //Credentials                     
    UsernamePasswordCredentials credentials = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP Basic authentication start");

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("HttpBasic: trying to get creds from repository ID: " + id);
    Credential httpBasicCred = null;
    try {
        httpBasicCred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (httpBasicCred != null) {
        credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword());
    } else {
        logger.debug("HttpBasic: trying to get creds from repository \"root\"");
        httpBasicCred = creds.getCredential("root");
        if (httpBasicCred != null) {
            logger.info("Trying with root credentails");
            credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(),
                    httpBasicCred.getPassword());
        }
    }

    logger.debug("Authenticating");
    Header[] headers = null;
    HttpMethodBase method = null;

    //Get Max connections
    int maxConnectionsPerHost = 30;
    int maxTotalConnections = 100;

    //Cookie Max Age
    int authMaxAge = -1;

    try {
        maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue();
        maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:");
        logger.error("  * maxConnectionsPerHost    * maxTotalConnections    * authMaxAge");
    }

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authentication process
    //

    // A fixed URL in the repository that all users have access to which can be used to authN a user
    // and capture the HTTP Authorization Header
    String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage");

    try {

        // Set HTTP headers
        headers = new Header[1];

        // Set User-Agent
        headers[0] = new Header("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5");

        // Request page, testing if credentials are valid
        if (credentials != null) {
            logger.debug("Username: " + credentials.getUserName());
            logger.debug("URL: " + authURL);
        }

        //HTTP request
        method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL);

        //Read the auth header and store in the cookie, the authZ class will use this later
        headers = method.getRequestHeaders();

        Header authHeader = null;
        authHeader = method.getRequestHeader("Authorization");

        // Cache status code
        if (method != null)
            statusCode = method.getStatusCode();

        if (statusCode == HttpServletResponse.SC_OK) {
            //Authentication worked, so create the auth cookie to indicate it has worked
            Cookie extAuthCookie = null;
            extAuthCookie = new Cookie(BASIC_COOKIE, "");

            if (authHeader != null) {

                String basicCookie = null;

                try {
                    basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder);
                    if (basicCookie == null) {
                        basicCookie = "";
                    }
                } catch (Exception ex) {
                    logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex);
                    basicCookie = "";
                }

                extAuthCookie.setValue(basicCookie);

            }
            String authCookieDomain = null;
            String authCookiePath = null;

            // Cache cookie properties
            authCookieDomain = valveConf.getAuthCookieDomain();
            authCookiePath = valveConf.getAuthCookiePath();

            // Set extra cookie parameters
            extAuthCookie.setDomain(authCookieDomain);
            extAuthCookie.setPath(authCookiePath);
            extAuthCookie.setMaxAge(authMaxAge);

            // Log info
            if (logger.isDebugEnabled())
                logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":"
                        + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":"
                        + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

            //sendCookies support                        
            boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled())
                    .booleanValue();
            boolean sendCookies = false;
            if (isSessionEnabled) {
                sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
            }
            if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
                logger.debug("Adding cookie to response");
                response.addCookie(extAuthCookie);
            }

            //Add cookies to the Cookie array to support sessions
            authCookies.add(extAuthCookie);
            logger.debug("Cookie added to the array");

        }

        // Clear webProcessor cookies
        webProcessor.clearCookies();

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Garbagge collect
        method = null;

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP Basic Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) {
        String domain = commonsCookie.getDomain();

        if (Validator.isNotNull(domain)) {
            cookie.setDomain(domain);//from ww w . j a  v  a2  s  .c  o  m
        }
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
        int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

        maxAge = maxAge / 1000;

        if (maxAge > -1) {
            cookie.setMaxAge(maxAge);
        }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
        cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpFields.java

/** Format a set cookie value
 * @param cookie The cookie.//  ww w  .j a  v a  2s  .c o  m
 */
public void addSetCookie(Cookie cookie) {
    String name = cookie.getName();
    String value = cookie.getValue();
    int version = cookie.getVersion();

    // Check arguments
    if (name == null || name.length() == 0)
        throw new IllegalArgumentException("Bad cookie name");

    // Format value and params
    StringBuffer buf = new StringBuffer(128);
    String name_value_params = null;
    synchronized (buf) {
        buf.append(name);
        buf.append('=');
        if (value != null && value.length() > 0) {
            if (version == 0)
                URI.encodeString(buf, value, "\";, '");
            else
                buf.append(QuotedStringTokenizer.quote(value, "\";, '"));
        }

        if (version > 0) {
            buf.append(";Version=");
            buf.append(version);
            String comment = cookie.getComment();
            if (comment != null && comment.length() > 0) {
                buf.append(";Comment=");
                QuotedStringTokenizer.quote(buf, comment);
            }
        }
        String path = cookie.getPath();
        if (path != null && path.length() > 0) {
            buf.append(";Path=");
            buf.append(path);
        }
        String domain = cookie.getDomain();
        if (domain != null && domain.length() > 0) {
            buf.append(";Domain=");
            buf.append(domain.toLowerCase());// lowercase for IE
        }
        long maxAge = cookie.getMaxAge();
        if (maxAge >= 0) {
            if (version == 0) {
                buf.append(";Expires=");
                if (maxAge == 0)
                    buf.append(__01Jan1970);
                else
                    formatDate(buf, System.currentTimeMillis() + 1000L * maxAge, true);
            } else {
                buf.append(";Max-Age=");
                buf.append(cookie.getMaxAge());
            }
        } else if (version > 0) {
            buf.append(";Discard");
        }
        if (cookie.getSecure()) {
            buf.append(";Secure");
        }
        if (cookie instanceof HttpOnlyCookie)
            buf.append(";HttpOnly");

        name_value_params = buf.toString();
    }
    put(__Expires, __01Jan1970);
    add(__SetCookie, name_value_params);
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

private void serializeCookies() throws Exception {
    Cookie[] cookies = req.getCookies();
    if (cookies != null && cookies.length > 0) {
        xsw.writeStartElement(URI, "cookies");
        for (Cookie cookie : cookies) {
            xsw.writeStartElement(URI, "cookie");
            dataElement(xsw, URI, "comment", cookie.getComment());
            dataElement(xsw, URI, "domain", cookie.getDomain());
            dataElement(xsw, URI, "max-age", Integer.toString(cookie.getMaxAge()));
            dataElement(xsw, URI, "name", cookie.getName());
            dataElement(xsw, URI, "path", cookie.getPath());
            dataElement(xsw, URI, "is-secure", Boolean.toString(cookie.getSecure()));
            dataElement(xsw, URI, "value", cookie.getValue());
            dataElement(xsw, URI, "version", Integer.toString(cookie.getVersion()));
            xsw.writeEndElement();/*from   w w  w  . j  a  v a 2s  . c om*/
        }
        xsw.writeEndElement();
    }
}

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

/**
 * Generate httponly cookie from HS2 cookie
 * @param cookie HS2 generated cookie/*from   w w  w. jav  a 2  s . com*/
 * @return The httponly cookie
 */
private static String getHttpOnlyCookieHeader(Cookie cookie) {
    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), cookie.getPath(),
            cookie.getDomain(), cookie.getVersion(), cookie.getComment(), cookie.getMaxAge(),
            cookie.getSecure());
    return newCookie + "; HttpOnly";
}