Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:cn.designthougths.sample.axon.sfav.webui.UIApplication.java

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override//from www.  ja  v  a2 s.  c om
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

public void deleteLoginCookie(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                if (cookie.getValue() != null && cookie.getValue().split(":").length == 2) {
                    LoginCookie loginCookie = loginCookieDAO.findByUUID(cookie.getValue().split(":")[0]);
                    if (loginCookie != null) {
                        loginCookieDAO.deleteById(loginCookie.getId());
                        break;
                    }//from ww  w . java 2 s .c om
                }
            }
        }
    }
    deleteCookie(request, response, null);
    deleteCookie(request, response, "/");
    deleteCookie(request, response, "/page");
    deleteCookie(request, response, "/admin");
    deleteCookie(request, response, "/login");
    deleteCookie(request, response, "/admin/events");
    deleteCookie(request, response, "/admin/events/edit");
    deleteCookie(request, response, "/events/event");
    Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, null);
    cookie.setDomain(request.getServerName());
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * csrf tokencookie/*www  . j ava 2s.  co m*/
 * 
 * @param request
 * @param response
 * @param tokenCode
 */
public void renderCSRFTokenInput(HttpServletRequest request, HttpServletResponse response,
        StringBuilder tokenCode) {
    String token = createToken();
    Cookie cookie = new Cookie(SESSION_TOKEN, token);
    response.addCookie(cookie);
    tokenCode.append("<input type=\"hidden\" name=\"").append(SESSION_TOKEN).append("\" value=\"").append(token)
            .append("\"/>");
    if (logger.isDebugEnabled()) {
        logger.debug("render csrf token value = " + token);
    }
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;/*w  ww. java2 s .c  o  m*/
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:m.c.m.proxyma.rewrite.CookieRewriteEngineTest.java

public void testMasquerade_Unmasquerade_Cookie() throws NullArgumentException, IllegalArgumentException, UnsupportedEncodingException {
    System.out.println("masquerade/unmasqueradeCookie");
    ProxymaFacade proxyma = new ProxymaFacade();
    ProxymaContext context = proxyma.getContextByName("default");
    ProxyFolderBean folder1 = proxyma.createNewProxyFolder("host1", "http://www.google.com/it", context);
    ProxyFolderBean folder2 = proxyma.createNewProxyFolder("host2", "https://www.apple.com/en", context);
    ProxymaResource aResource = proxyma.createNewResource(request, response, context);
    aResource.setProxymaRootURI("http://localhost:8080/proxyma");
    aResource.setProxyFolder(folder1);//  w w w  . ja  v  a2  s .com
    CookieRewriteEngine instance = new CookieRewriteEngine(context);

    Cookie theCookie = new Cookie("cookie1", "Value1");
    theCookie.setDomain("google.com");
    theCookie.setPath("/it/pippo");
    instance.masqueradeCookie(theCookie, aResource);

    String expected = "localhost";
    assertEquals(expected, theCookie.getDomain());

    expected = "/proxyma/host1/pippo";
    assertEquals(expected, theCookie.getPath());

    expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER  + "Value1";
    assertEquals(expected, theCookie.getValue());

    instance.unmasqueradeCookie(theCookie);

    expected = "Value1";
    assertEquals(expected, theCookie.getValue());

    theCookie = new Cookie("cookie2", "Value2");
    instance.masqueradeCookie(theCookie, aResource);

    expected = "localhost";
    assertEquals(expected, theCookie.getDomain());

    expected = "/proxyma/host1";
    assertEquals(expected, theCookie.getPath());

    expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER  + "Value2";
    assertEquals(expected, theCookie.getValue());

    instance.unmasqueradeCookie(theCookie);

    expected = "Value2";
    assertEquals(expected, theCookie.getValue());

    proxyma.removeProxyFolder(folder2, context);
    proxyma.removeProxyFolder(folder1, context);
}

From source file:com.google.acre.script.AcreCookie.java

public Cookie toServletCookie() {
    Cookie c = new Cookie(name, value);
    c.setPath(path);//from w w  w  .j av  a 2 s .com
    c.setMaxAge(max_age);
    if (domain != null)
        c.setDomain(domain);
    c.setSecure(secure);
    return c;
}

From source file:org.zaizi.sensefy.auth.LoginConfig.java

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {

        @Override/*from  w w  w .  ja v a2  s . c  om*/
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {

                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    // response.setHeader("Access-Control-Allow-Origin",
                    // "*");
                    // response.setHeader("Access-Control-Allow-Methods",
                    // "POST, GET, OPTIONS, DELETE");
                    // response.setHeader("Access-Control-Max-Age",
                    // "3600");
                    // response.setHeader("Access-Control-Allow-Headers",
                    // "x-requested-with");
                }

            }
            filterChain.doFilter(request, response);
        }
    };
}

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  ww w.  ja  v  a  2s. com*/
 * 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:com.epam.cme.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDefaultPath() {
    cookieGenerator.setCookieName("guid");
    cookieGenerator.setHttpOnly(true);// server side

    BDDMockito.given(request.getContextPath()).willReturn("/some_path");

    cookieGenerator.addCookie(request, response, "cookie_monster");

    final Cookie expectedCookie = new Cookie("guid", "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);//from   w  ww.  j  ava2  s  .co m
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "guid=cookie_monster; Domain=\"what a domain\"; Path=/; HttpOnly");

}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDefaultPath() {
    cookieGenerator.setCookieName("guid");
    cookieGenerator.setHttpOnly(true);//server side

    BDDMockito.given(request.getContextPath()).willReturn("/some_path");

    cookieGenerator.addCookie(request, response, "cookie_monster");

    final Cookie expectedCookie = new Cookie("guid", "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);// w  ww.java  2s  .c o  m
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie)));
    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "guid=cookie_monster; Domain=\"what a domain\"; Path=/; HttpOnly");

}