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:au.org.paperminer.main.UserFilter.java

/**
 * Effectively logs out the user//from ww w. ja va 2  s.  co  m
 * @param resp
 */
private void removeCookie(HttpServletResponse resp) {
    Cookie cookie = new Cookie(PaperMinerConstants.PM_COOKIE, "");
    cookie.setMaxAge(0);
    resp.addCookie(cookie);
}

From source file:com.vmware.demo.HomeController.java

@RequestMapping(value = "/sso", method = RequestMethod.POST)
public String generateRequest(HttpServletRequest request, HttpServletResponse response, Locale locale,
        Model model, String action, String SAMLResponse, String SAMLCertificate, String idpUri, String samlCert,
        String s, String i, String nameIdFormat, String consumeUrl) {
    String serviceProviderId = (String) request.getSession().getAttribute(ATTRIBUTE_SP_ID);

    // SETUP TEST
    if ("setup".equals(action)) {
        logger.info("Setup test");

        // Pass along the standard set
        model.addAttribute(ATTRIBUTE_IDP_ID, identityProviderId);
        model.addAttribute(ATTRIBUTE_SP_ID, serviceProviderId);
        model.addAttribute(ATTRIBUTE_IDP_URI, idpUri);
        model.addAttribute("nameIdFormat", DEFAULT_NAMEID_FORMAT);
        model.addAttribute("consumeUrl", idpUri + CONSUME_REQUEST);

        // Set in a cookie for next time you come back
        Cookie cookie = new Cookie(COOKIE_NAME, idpUri);
        response.addCookie(cookie);/*from www .  ja v a2s .c  om*/

        if (null != samlCert) {
            logger.info("Setup test using uploaded certificate.");
            try {
                if (StringUtils.isNotEmpty(samlCert)) {
                    samlCert = SamlUtils.convertToPemFormat(SamlUtils.parsePemCertificate(samlCert));
                } else {
                    model.addAttribute(ATTRIBUTE_ERROR_MSG,
                            "Saml certificate not provided, no validation will be done.");
                }
            } catch (SamlException e) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG,
                        "Failed to parse certificate. " + e.getLocalizedMessage());
                model.addAttribute(ATTRIBUTE_ACTION, "setupcert");
                return "home";
            }
        } else {
            logger.info("Setup test using meta data url.");
            samlCert = SamlService.getInstance().loadSigningKeyFromMetaData(idpUri + METADATA_REQUEST);
            if (null == samlCert) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG, "Failed to contact service at " + idpUri
                        + ", please fetch and upload certificate manually.");
                model.addAttribute(ATTRIBUTE_ACTION, "setupcert");
                return "home";
            }
        }

        // Save to session
        if (!StringUtils.isEmpty(idpUri)) {
            request.getSession().setAttribute(ATTRIBUTE_IDP_URI, idpUri);
        }
        if (!StringUtils.isEmpty(samlCert)) {
            request.getSession().setAttribute(ATTRIBUTE_SAML_CERT, samlCert);
        }
        if (!StringUtils.isEmpty(s)) {
            request.getSession().setAttribute(ATTRIBUTE_SP_ID, s);
        }

        model.addAttribute(ATTRIBUTE_ACTION, "generaterequest");
    }

    // GENERATE SAML REQUEST
    if ("generaterequest".equals(action)) {
        logger.info("Generating authnRequest");

        String authnRequest = SamlService.getInstance().generateSAMLRequest(CONSUMER_URI, nameIdFormat);

        model.addAttribute("consumeUrl", consumeUrl);
        model.addAttribute(ATTRIBUTE_IDP_URI, idpUri);
        model.addAttribute(ATTRIBUTE_AUTHN_REQUEST, authnRequest);
        model.addAttribute(ATTRIBUTE_RELAY_STATE, RELAY_STATE);
        model.addAttribute(ATTRIBUTE_IDP_ID, null != i ? i : identityProviderId);
        model.addAttribute(ATTRIBUTE_SP_ID, null != s ? s : serviceProviderId);
        model.addAttribute(ATTRIBUTE_SAML_CERTIFICATE, SAMLCertificate);
        model.addAttribute(ATTRIBUTE_ACTION, "sendrequest");
    }

    // VALIDATE SAML RESPONSE
    if (null != SAMLResponse) {

        logger.info(SAMLResponse);
        String decodedResponse;
        String relayState;
        String target;
        try {
            samlCert = (String) request.getSession().getAttribute(ATTRIBUTE_SAML_CERT);
            relayState = (String) request.getParameter(ATTRIBUTE_RELAY_STATE);
            target = (String) request.getParameter(ATTRIBUTE_TARGET);
            model.addAttribute(ATTRIBUTE_RELAY_STATE, relayState);
            model.addAttribute(ATTRIBUTE_TARGET, target);

            List<IdentityProvider> identityProviders = organizationHandler.getAllIdentityProviders();
            if (null == samlCert) {
                decodedResponse = SamlService.getInstance().validateSAMLResponse(SAMLResponse,
                        identityProviders);
            } else {
                decodedResponse = SamlService.getInstance().validateSAMLResponse(SAMLResponse, samlCert);
            }

            if (StringUtils.isBlank(decodedResponse)) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG, "Failed to validate SAML Response");
                model.addAttribute("SAMLResponse", decodedResponse);
            } else {
                model.addAttribute(ATTRIBUTE_SUCCESS_MSG, "SAML Response validated.");
                model.addAttribute("SAMLResponse", decodedResponse);
            }
        } catch (Exception e) {
            model.addAttribute("SAMLResponse", SAMLResponse);
            model.addAttribute(ATTRIBUTE_ERROR_MSG, e.getLocalizedMessage());
        }
    }

    return "home";
}

From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();/*from   ww  w .j  av  a2 s .com*/
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie")
                            || header.getName().equalsIgnoreCase("set-cookie2")) {
                        //System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
                           cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                        }
                                
                        //System.out.println(cookieVal);*/

                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}

From source file:com.vmware.identity.openidconnect.server.LogoutRequestProcessor.java

private Cookie personUserCertificateLoggedOutCookie() {
    Cookie cookie = new Cookie(SessionManager.getPersonUserCertificateLoggedOutCookieName(this.tenant), "");
    cookie.setPath("/openidconnect");
    cookie.setSecure(true);/* w  w  w  .  jav a  2 s .  co m*/
    cookie.setHttpOnly(true);
    return cookie;
}

From source file:com.appeligo.search.actions.BaseAction.java

protected void setLineup(String lineup) {
    getServletRequest().getSession().setAttribute(LINEUP_ID, lineup);
    Cookie cookie = new Cookie(LINEUP_ID, lineup);
    cookie.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(cookie);//from   w  w  w .  j a v  a2 s.  c  o m
}

From source file:org.ngrinder.user.controller.UserController.java

/**
 * Switch user identity./*  w  w  w .  j a  va  2  s .  co m*/
 *
 * @param model    model
 * @param to       the user to whom a user will switch
 * @param response response
 * @return redirect:/perftest/
 */
@RequestMapping("/switch")
public String switchUser(@RequestParam(required = false, defaultValue = "") String to,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    Cookie cookie = new Cookie("switchUser", to);
    cookie.setPath("/");
    // Delete Cookie if empty switchUser
    if (StringUtils.isEmpty(to)) {
        cookie.setMaxAge(0);
    }

    response.addCookie(cookie);
    model.clear();
    final String referer = request.getHeader("referer");
    return "redirect:" + StringUtils.defaultIfBlank(referer, "/");
}

From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptorTest.java

private MockHttpServletRequest requestWithCookies() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    Cookie cookie = new Cookie("_ZopeId", "\"68673848A6sbSTxqyEQ\"");
    Cookie[] cookies = { cookie };/*from  www  .j a v a2 s. c o m*/
    request.setCookies(cookies);
    return request;
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerOptionalTest.java

@Test
public void testMethod16() {
    List<Cookie> cookies = new ArrayList<Cookie>();
    cookies.add(new Cookie("intCookie", "1"));
    cookies.add(new Cookie("booleanCookie", "true"));
    ControllerUtil.sendAndReceive(mockMvc, null, cookies, "remoteProviderOptional", "method16", "1;true",
            (Object[]) null);/*from   ww w . j  a  v  a  2  s .c om*/
    ControllerUtil.sendAndReceive(mockMvc, null, null, "remoteProviderOptional", "method16", "-1;false",
            (Object[]) null);
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Creates an authentication request, authenticates the user and, if
 * successful, returns the user's credentials.
 * /*from w  ww  .j av a2  s.  com*/
 * @param username
 *        The username of the user attempting to authenticate.
 * 
 * @param password
 *        The password of the user attempting to authenticate.
 * 
 * @param request
 *        The HTTP request object.
 * 
 * @param response
 *        The HTTP response object.
 * 
 * @return The authorization token.
 * 
 * @throws OmhException
 *         There was a problem with the request. This could be any of the
 *         sub-classes of {@link OmhException}.
 */
@RequestMapping(value = "auth", method = RequestMethod.POST)
public @ResponseBody String getAuthentication(
        @RequestParam(value = PARAM_AUTHENTICATION_USERNAME, required = true) final String username,
        @RequestParam(value = PARAM_AUTHENTICATION_PASSWORD, required = true) final String password,
        final HttpServletRequest request, final HttpServletResponse response) throws OmhException {

    // Create the authentication request from parameters.
    AuthenticationToken token = handleRequest(request, response, new AuthenticationRequest(username, password));

    // Add a cookie for the authentication token.
    Cookie cookie = new Cookie(PARAM_AUTHENTICATION_AUTH_TOKEN, token.getToken());
    // Set the expiration on the cookie.
    cookie.setMaxAge(new Long((token.getExpires() - System.currentTimeMillis()) / 1000).intValue());
    // Build the path without the "auth" part.
    String requestUri = request.getRequestURI();
    cookie.setPath(requestUri.substring(0, requestUri.length() - 5));
    // Make sure the cookie is only used with HTTPS.
    cookie.setSecure(true);
    // Add the cookie to the response.
    response.addCookie(cookie);

    // Return the token.
    return token.getToken();
}

From source file:com.appeligo.search.actions.BaseAction.java

protected void setTimeZone(TimeZone timeZone) {
    getServletRequest().getSession().setAttribute(TIMEZONE_ID, timeZone);
    Cookie cookie = new Cookie(TIMEZONE_ID, timeZone.getID());
    cookie.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(cookie);/*from   w w  w  .j  ava2s  .com*/
}