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:com.qut.middleware.esoe.authn.servlet.AuthnServlet.java

/**
 * Iteraties through all cookies presented by user request and retrieves details about SSO and any current session
 * /*from  w  ww .  ja va2  s  .c o  m*/
 * @param data
 *            Local request AuthnProcessoreData bean
 */
private void processCookies(AuthnProcessorData data) {
    Cookie[] cookies = data.getHttpRequest().getCookies();
    if (cookies != null) {
        this.logger.debug(Messages.getString("AuthnServlet.20")); //$NON-NLS-1$
        for (Cookie cookie : cookies) {
            this.logger.debug(Messages.getString("AuthnServlet.21") + cookie.getName() //$NON-NLS-1$
                    + Messages.getString("AuthnServlet.22") + cookie.getValue()); //$NON-NLS-1$
            /* Allow automated handlers to not perform any function if user demands manual input */
            if (cookie.getName().equals(this.disableSSOTokenName) && cookie.getValue().equals("true")) //$NON-NLS-1$
            {
                this.logger.debug(Messages.getString("AuthnServlet.23")); //$NON-NLS-1$
                data.setAutomatedSSO(false);
            }
            if (cookie.getName().equals(this.sessionTokenName)) {
                data.setSessionID(cookie.getValue());
            }
        }
    }
}

From source file:com.laxser.blitz.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }//from   ww w .j a  va  2  s  .  c  o  m
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java

@Override
public void addCookie(final HttpServletResponse response, final String cookieValue) {
    super.addCookie(new HttpServletResponseWrapper(response) {
        @Override//  ww w  .ja  v a  2s  .c  om
        public void addCookie(final Cookie cookie) {
            setEnhancedCookiePath(cookie);

            if (isHttpOnly()) {
                // Custom code to write the cookie including the httpOnly flag
                final StringBuffer headerBuffer = new StringBuffer(100);
                ServerCookie.appendCookieValue(headerBuffer, cookie.getVersion(), cookie.getName(),
                        cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(),
                        cookie.getMaxAge(), cookie.getSecure(), true);
                response.addHeader(HEADER_COOKIE, headerBuffer.toString());
            } else {
                // Write the cookie as normal
                super.addCookie(cookie);
            }
        }
    }, cookieValue);
}

From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java

private Cookie getCookie(Cookie[] cookies, String name) {
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (name.equals(cookie.getName())) {
                return cookie;
            }/*from  w  w w . j a  va  2s  .c  o  m*/
        }
    }
    return null;
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ?cookie//from www  . jav  a2 s . co m
 * 
 * @param resp
 * @param copyToSession
 *            ??session
 * @param cookies
 */
public static void save(HttpServletRequest req, HttpServletResponse resp, boolean copyToSession,
        Cookie... cookies) {
    HttpSession session = req.getSession(true);
    for (Cookie cookie : cookies) {
        resp.addCookie(cookie);
        if (copyToSession)
            session.setAttribute(cookie.getName(), cookie.getValue());
    }
}

From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map requestMap = HttpServletHelper.getInstance().createRequestMap(request);
    Map session = HttpServletHelper.getInstance().createSessionMap(request);
    Map application = HttpServletHelper.getInstance().createApplicationMap(request);

    ModelAndView returnedMv;/* w ww . j av  a2s  .c  om*/

    if (controller instanceof CancelableController
            && ((CancelableController) controller).isCancel(requestMap)) {
        returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application,
                command, errors);
    } else {
        returnedMv = controller.handleRequest(command, requestMap, session, application, errors);
    }

    boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false);

    if (errors.hasErrors()) {
        logger.debug("Form submission errors: " + errors.getErrorCount());
        HttpServletHelper.getInstance().reloadApplicationMap(request, application);
        HttpServletHelper.getInstance().reloadSessionMap(request, session);
        HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);
        if (saveCookies) {
            Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes");
            cookie.setMaxAge(30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return showForm(request, response, errors);
    }

    if (returnedMv.getViewName() != null) {
        // should get from mappings
        String mappedView = (String) screenMappings.get(returnedMv.getViewName());

        if (mappedView == null) {
            mappedView = returnedMv.getViewName();
        }

        //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView);

        returnedMv = new ModelAndView(mappedView, returnedMv.getModel());
    }

    //We have a successful save coming back, so we set/append to a cookie
    String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS);
    if (savedForm != null && saveCookies) {
        Cookie cookie = null;
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) {
                    String[] forms = c.getValue().split(",");
                    StringBuilder value = new StringBuilder();
                    boolean alreadyIncluded = false;
                    for (String form : forms) {
                        if (form.equals(savedForm)) {
                            alreadyIncluded = true;
                        }
                        value.append(",").append(form);
                    }
                    if (!alreadyIncluded) {
                        value.append(",").append(savedForm);
                    }
                    cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1));
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm);
        }
        cookie.setMaxAge(2000000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    HttpServletHelper.getInstance().reloadApplicationMap(request, application);
    HttpServletHelper.getInstance().reloadSessionMap(request, session);
    HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);

    return returnedMv;
}

From source file:aaf.vhr.idp.http.VhrRemoteUserAuthServlet.java

/** {@inheritDoc} */
@Override/*from   ww w.j  a  v a 2 s.com*/
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        // key to ExternalAuthentication session
        String key = null;
        boolean isVhrReturn = false;
        boolean isForceAuthn = false;
        DateTime authnStart = null; // when this authentication started at the IdP
        // array to use as return parameter when calling VhrSessionValidator
        DateTime authnInstantArr[] = new DateTime[1];

        if (httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME) != null) {
            // we have come back from the VHR
            isVhrReturn = true;
            key = httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME);
            HttpSession hs = httpRequest.getSession();

            if (hs != null && hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key) != null) {
                authnStart = (DateTime) hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key);
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

            if (hs != null && hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key) != null) {
                isForceAuthn = ((Boolean) hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key)).booleanValue();
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

        } else {
            // starting a new SSO request
            key = ExternalAuthentication.startExternalAuthentication(httpRequest);

            // check if forceAuthn is set
            Object forceAuthnAttr = httpRequest.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM);
            if (forceAuthnAttr != null && forceAuthnAttr instanceof java.lang.Boolean) {
                log.debug("Loading foceAuthn value");
                isForceAuthn = ((Boolean) forceAuthnAttr).booleanValue();
            }

            // check if we can see when authentication was initiated
            final AuthenticationContext authCtx = ExternalAuthentication
                    .getProfileRequestContext(key, httpRequest)
                    .getSubcontext(AuthenticationContext.class, false);
            if (authCtx != null) {
                log.debug("Authentication initiation is {}", authCtx.getInitiationInstant());
                authnStart = new DateTime(authCtx.getInitiationInstant(), DateTimeZone.UTC);
                log.debug("AuthnStart is {}", authnStart);
            }
            ;

        }
        ;
        log.debug("forceAuthn is {}, authnStart is {}", isForceAuthn, authnStart);

        if (key == null) {
            log.error("No ExternalAuthentication sesssion key found");
            throw new ServletException("No ExternalAuthentication sesssion key found");
        }
        ;
        // we now have a key - either:
        // * we started new authentication
        // * or we have returned from VHR and loaded the key from the HttpSession

        String username = null;

        // We may have a cookie - either as part of return or from previous session
        // Attempt to locate VHR SessionID
        String vhrSessionID = null;
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SSO_COOKIE_NAME)) {
                vhrSessionID = cookie.getValue();
                break;
            }
        }

        if (vhrSessionID != null) {
            log.info("Found vhrSessionID from {}. Establishing validity.", httpRequest.getRemoteHost());
            username = vhrSessionValidator.validateSession(vhrSessionID, (isForceAuthn ? authnStart : null),
                    authnInstantArr);
        }
        ;

        // If we do not have a username yet (no Vhr session cookie or did not validate),
        // we redirect to VHR - but only if we are not returning from the VHR
        // Reason: (i) we do not want to loop and (ii) we do not have the full context otherwise initialized by
        // ExternalAuthentication.startExternalAuthentication()
        if (username == null && !isVhrReturn) {

            URLCodec codec = new URLCodec();
            String relyingParty = (String) httpRequest.getAttribute("relyingParty");
            String serviceName = "";

            log.info("No vhrSessionID found from {}. Directing to VHR authentication process.",
                    httpRequest.getRemoteHost());
            log.debug("Relying party which initiated the SSO request was: {}", relyingParty);

            // try getting a RelyingPartyUIContext
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final RelyingPartyUIContext rpuiCtx = prc.getSubcontext(AuthenticationContext.class, true)
                    .getSubcontext(RelyingPartyUIContext.class, false);
            if (rpuiCtx != null) {
                serviceName = rpuiCtx.getServiceName();
                log.debug("RelyingPartyUIContext received, ServiceName is {}", serviceName);
            }
            ;

            // save session *key*
            HttpSession hs = httpRequest.getSession(true);
            hs.setAttribute(IS_FORCE_AUTHN_ATTR_NAME + key, new Boolean(isForceAuthn));
            hs.setAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key, authnStart);

            try {
                httpResponse.sendRedirect(String.format(vhrLoginEndpoint,
                        codec.encode(httpRequest.getRequestURL().toString() + "?" + REDIRECT_REQ_PARAM_NAME
                                + "=" + codec.encode(key)),
                        codec.encode(relyingParty), codec.encode(serviceName)));
            } catch (EncoderException e) {
                log.error("Could not encode VHR redirect params");
                throw new IOException(e);
            }
            return; // we issued a redirect - return now
        }
        ;

        if (username == null) {
            log.warn("VirtualHome authentication failed: no username received");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    "VirtualHome authentication failed: no username received");
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        // check if consent revocation was requested
        String consentRevocationParam = httpRequest.getParameter(consentRevocationParamName);
        if (consentRevocationParam != null) {
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final ConsentManagementContext consentCtx = prc.getSubcontext(ConsentManagementContext.class, true);
            log.debug("Consent revocation request received, setting revokeConsent in consentCtx");
            consentCtx.setRevokeConsent(consentRevocationParam.equalsIgnoreCase("true"));
        }
        ;

        // Set authnInstant to timestamp returned by VHR
        if (authnInstantArr[0] != null) {
            log.debug("Response from VHR includes authenticationInstant time {}, passing this back to IdP",
                    authnInstantArr[0]);
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_INSTANT_KEY, authnInstantArr[0]);
        }
        ;

        httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username);

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:eu.eidas.node.AbstractNodeServlet.java

/**
 * Sets HTTPOnly Header on the session to prevent cookies from being accessed through
 * client-side script.//from   w  w w.j a  v a 2  s  .co  m
 *
 * @param renewSession indicates that the session cookie will be renewed
 */
protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request,
        HttpServletResponse response) {
    if (request != null && request.getSession(false) != null) {
        // Renewing the session if necessary
        String currentSession = null;
        String messageLog = null;
        if (renewSession) {
            currentSession = sessionIdRegenerationInWebApp(request);
            messageLog = "http session Renewed : {}";
        } else {
            currentSession = request.getSession().getId();
            messageLog = "http session obtained from request : {}";
        }
        MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession);
        getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession);
        // changing session cookie to http only cookie
        if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) {
            //Session Id requested by the client, obtained from the cookie
            final String requestedSessionId = request.getRequestedSessionId();
            for (Cookie cookie : request.getCookies()) {
                getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]",
                        cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue());
                if (currentSession.equals(requestedSessionId)) {
                    // Removes old version
                    boolean isSecure = request.isSecure();
                    getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}",
                            cookie.toString());
                    getLogger().debug("Is using SSL?", isSecure);

                    //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header
                    //
                    //NOSONAR                        cookie.setMaxAge(0);
                    //NOSONAR                        cookie.setPath(getServletContext().getContextPath());
                    //NOSONAR                 cookie.setDomain(request.getServerName());
                    //NOSONAR                 cookie.setSecure(isSecure);
                    //NOSONAR                 cookie.setHttpOnly(true);
                    //NOSONAR                 response.addCookie(cookie);

                    // Create new one httpOnly
                    StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName())
                            .append(EIDASValues.EQUAL.toString()).append(cookie.getValue())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString())
                            .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString())
                            .append(" ").append(EIDASValues.PATH.toString())
                            .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString())
                            .append(isSecure ? EIDASValues.SECURE.toString() : "");
                    response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString());
                }
            }
        }
        //cookie _csrf
        //            request.setAttribute("_csrf_header", "X-CSRF-TOKEN");
        //            UUID idOne = UUID.randomUUID();
        //            LOG.info("generate csrf id="+idOne);
        //            request.setAttribute("_csrf", idOne);
        response.setHeader("_csrf_header", "X-CSRF-TOKEN");
        UUID idOne = UUID.randomUUID();
        UUID idTwo = UUID.randomUUID();
        getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo);
        Cookie gato = new Cookie("_csrf", idOne.toString());
        response.addCookie(gato);
        response.setHeader("X-CSRF-TOKEN", idTwo.toString());

    } else {
        getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !");
    }
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

private JSONObject fromCookie(HttpServletRequest request) throws JSONException {
    if (useCookies) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (COOKIENAME.equals(cookie.getName())) {
                    Base64 decoder = new Base64();
                    try {
                        return new JSONObject(new String(decoder.decode(cookie.getValue()), "UTF-8"));
                    } catch (UnsupportedEncodingException ex) {
                        log(ex.getMessage(), ex);
                        return new JSONObject();
                    }/*from   w  w w.  j  a  va  2s .  c  om*/
                }
            }
        }
    }
    return new JSONObject();

}

From source file:gr.abiss.calipso.userDetails.controller.UserDetailsController.java

@RequestMapping(method = RequestMethod.GET)
@ResponseBody/*from  w w w  . ja va  2s . c om*/
public ICalipsoUserDetails remember() {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("remember");
    }

    UserDetails resource = new UserDetails();

    Cookie tokenCookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {

        for (int i = 0; i < cookies.length; i++) {
            tokenCookie = cookies[i];
            if (tokenCookie.getName().equals(this.userDetailsConfig.getCookiesBasicAuthTokenName())) {
                String token = tokenCookie.getValue();
                if (StringUtils.isNotBlank(token)) {
                    token = new String(Base64.decode(token.getBytes()));
                    LOGGER.info("Request contained token: " + token);
                    if (token.indexOf(':') > 0) {
                        String[] parts = token.split(":");
                        if (StringUtils.isNotBlank(parts[0]) && StringUtils.isNotBlank(parts[1])) {
                            resource.setUsername(parts[0]);
                            resource.setPassword(parts[1]);
                        }
                    } else {
                        LOGGER.warn("Invalid token received: " + token);
                    }
                }
                break;
            }
        }
    }
    return this.create(resource);

}