Example usage for javax.servlet.http Cookie setSecure

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

Introduction

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

Prototype

public void setSecure(boolean flag) 

Source Link

Document

Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

Usage

From source file:io.mapzone.controller.vm.http.LoginProvision.java

protected void registerUser(String userId, @SuppressWarnings("hiding") HttpServletResponse response) {
    // cookie token
    byte[] bytes = new byte[8];
    rand.nextBytes(bytes);/*from  w w w  .j  a v  a  2  s  .c  om*/
    String token = Base64.encodeBase64URLSafeString(bytes);

    // FIXME Leak: entries are never removed (allow just one cookie/session per user?)
    if (loggedIn.putIfAbsent(token, userId) != null) {
        throw new IllegalStateException("Token already exists: " + token);
    }

    // set cookie
    Cookie newCookie = new Cookie(COOKIE_NAME, token);
    newCookie.setHttpOnly(true);
    newCookie.setPath(COOKIE_PATH);
    newCookie.setSecure(false); // XXX
    newCookie.setMaxAge(COOKIE_MAX_AGE);
    response.addCookie(newCookie);
}

From source file:cec.easyshop.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testClientSideCookieDefaultPath() {
    cookieGenerator.setCookieName(JSESSIONID);
    cookieGenerator.setHttpOnly(false);//client side
    cookieGenerator.addCookie(response, "cookie_monster");
    final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    assertNoHeaderAdjustments();//from   w  w w  . ja v  a 2s .c o  m
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01032.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    javax.servlet.http.Cookie[] theCookies = request.getCookies();

    String param = null;/* w w  w . j  a v a  2  s . c  o m*/
    boolean foundit = false;
    if (theCookies != null) {
        for (javax.servlet.http.Cookie theCookie : theCookies) {
            if (theCookie.getName().equals("vector")) {
                param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
                foundit = true;
            }
        }
        if (!foundit) {
            // no cookie found in collection
            param = "";
        }
    } else {
        // no cookies
        param = "";
    }

    String bar = new Test().doSomething(param);

    try {
        long l = java.security.SecureRandom.getInstance("SHA1PRNG").nextLong();
        String rememberMeKey = Long.toString(l);

        String user = "SafeLogan";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
            javax.servlet.http.Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                    foundUser = true;
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");
        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextLong() - TestCase");
        throw new ServletException(e);
    }
    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextLong() executed");
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01914.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    javax.servlet.http.Cookie[] theCookies = request.getCookies();

    String param = null;/*  w w w .j a v  a  2 s  .  com*/
    boolean foundit = false;
    if (theCookies != null) {
        for (javax.servlet.http.Cookie theCookie : theCookies) {
            if (theCookie.getName().equals("vector")) {
                param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
                foundit = true;
            }
        }
        if (!foundit) {
            // no cookie found in collection
            param = "";
        }
    } else {
        // no cookies
        param = "";
    }

    String bar = doSomething(param);

    try {
        double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();

        String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.

        String user = "SafeDonna";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
            javax.servlet.http.Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                    foundUser = true;
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");
        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
        throw new ServletException(e);
    }

    response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}

From source file:co.id.app.sys.util.StringUtils.java

/**
 * Sets the given cookie values in the servlet response.
 * <p/>//from ww w  .  ja  va2s . c  om
 * This will also put the cookie in a list of cookies to send with this request's response
 * (so that in case of a redirect occurring down the chain, the first filter
 * will always try to set this cookie again)
 * <p/>
 * The cookie secure flag is set if the request is secure.
 * <p/>
 * This method was derived from Atlassian <tt>CookieUtils</tt> method of
 * the same name, release under the Apache License.
 *
 * @param request the servlet request
 * @param response the servlet response
 * @param name the cookie name
 * @param value the cookie value
 * @param maxAge the maximum age of the cookie in seconds. A negative
 * value will expire the cookie at the end of the session, while 0 will delete
 * the cookie.
 * @param path the cookie path
 * @return the Cookie object created and set in the response
 */
public static Cookie setCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, int maxAge, String path) {

    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    cookie.setPath(path);
    cookie.setSecure(request.isSecure());
    response.addCookie(cookie);

    return cookie;
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00583.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getParameterNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        String[] values = request.getParameterValues(name);
        if (values != null) {
            for (int i = 0; i < values.length && flag; i++) {
                String value = values[i];
                if (value.equals("BenchmarkTest00583")) {
                    param = name;/*  www .  ja  v a  2 s.  co m*/
                    flag = false;
                }
            }
        }
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; !foundUser && i < cookies.length; i++) {
                javax.servlet.http.Cookie cookie = cookies[i];
                if (cookieName.equals(cookie.getName())) {
                    if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                        foundUser = true;
                    }
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");

        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            //         rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
            rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
            // e.g., /benchmark/sql-01/BenchmarkTest01001
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01167.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        java.util.Enumeration<String> values = request.getHeaders(name);
        if (values != null) {
            while (values.hasMoreElements() && flag) {
                String value = (String) values.nextElement();
                if (value.equals("vector")) {
                    param = name;/*  w  w  w  . j a v  a  2 s .c om*/
                    flag = false;
                }
            }
        }
    }

    String bar = new Test().doSomething(param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
            javax.servlet.http.Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                    foundUser = true;
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");
        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01860.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    javax.servlet.http.Cookie userCookie = new javax.servlet.http.Cookie("BenchmarkTest01860", "whatever");
    userCookie.setMaxAge(60 * 3); //Store cookie for 3 minutes
    userCookie.setSecure(true);
    userCookie.setPath(request.getRequestURI());
    response.addCookie(userCookie);/*from  ww  w  .  j  av a 2 s . c o m*/
    javax.servlet.RequestDispatcher rd = request.getRequestDispatcher("/weakrand-04/BenchmarkTest01860.html");
    rd.include(request, response);
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01869.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    javax.servlet.http.Cookie[] theCookies = request.getCookies();

    String param = "noCookieValueSupplied";
    if (theCookies != null) {
        for (javax.servlet.http.Cookie theCookie : theCookies) {
            if (theCookie.getName().equals("BenchmarkTest01869")) {
                param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
                break;
            }//from   w w  w . j  a v a  2  s.  co m
        }
    }

    String bar = doSomething(request, param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; !foundUser && i < cookies.length; i++) {
                javax.servlet.http.Cookie cookie = cookies[i];
                if (cookieName.equals(cookie.getName())) {
                    if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                        foundUser = true;
                    }
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");

        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            //         rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
            rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
            // e.g., /benchmark/sql-01/BenchmarkTest01001
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:cec.easyshop.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDynamicPath() {
    cookieGenerator.setCookieName(JSESSIONID);
    cookieGenerator.setHttpOnly(true);//server side
    cookieGenerator.setUseDefaultPath(false);
    BDDMockito.given(request.getContextPath()).willReturn("/some_path");
    cookieGenerator.addCookie(response, "cookie_monster");

    final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster");
    expectedCookie.setPath("/some_path");
    expectedCookie.setSecure(false);
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "JSESSIONID=cookie_monster; Version=1; Domain=\"what a domain\"; Path=/some_path; HttpOnly");
}