Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchByDate(HttpServletRequest request, HttpServletResponse response) {
    Cookie sbdCookie = null;

    String searchByDate = request.getParameter("searchByDate");
    if (searchByDate == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchByDate")) {
                sbdCookie = c;/*from ww  w.j  av  a  2  s  .  c  o  m*/
            }
        }
        if (sbdCookie != null) {
            searchByDate = sbdCookie.getValue();
        } else {
            searchByDate = new SimpleDateFormat("dd.MM.yyyy").format(Calendar.getInstance().getTime());
        }
    } else {
        sbdCookie = new Cookie("searchByDate", searchByDate);
        sbdCookie.setPath("/");
        response.addCookie(sbdCookie);
    }
    return searchByDate;
}

From source file:io.stallion.plugins.flatBlog.contacts.ContactsEndpoints.java

@POST
@Path("/contacts/submit-form")
public Boolean submitForm(@ObjectParam FormSubmission rawSubmission) {
    FormSubmission submission = SafeMerger.with().nonEmpty("data")
            .optional("formName", "pageUrl", "pageTitle", "formId").optionalEmail("email").merge(rawSubmission);
    Cookie everCookie = Context.request().getCookie("st-evercookie");
    Contact contact = null;//from   ww w. j  a  va 2 s. com
    if (!empty(submission.getEmail())) {
        contact = ContactsController.instance().forUniqueKey("email", submission.getEmail());
    } else if (empty(submission.getEmail()) && everCookie != null && !empty(everCookie.getValue())) {
        contact = ContactsController.instance().forUniqueKey("everCookie", everCookie.getValue());
        submission.setEmail(contact.getEmail());
    }
    if (empty(submission.getEmail())) {
        throw new ClientException("A valid email is required to submit a form to the contacts endpoint!", 422);
    }
    if (contact == null) {
        contact = new Contact().setEmail(submission.getEmail());
    }
    if (everCookie == null || empty(everCookie.getValue()) && empty(contact.getEverCookie())) {
        contact.setEverCookie(UUID.randomUUID().toString());
    }
    Context.response().addCookie("st-evercookie", contact.getEverCookie(), 365 * 20 * 86400);

    for (Map.Entry<String, Object> entry : submission.getData().entrySet()) {
        if (PropertyUtils.isWriteable(contact, entry.getKey())) {
            if (Contact.SETTABLE_FIELDS.contains(entry.getKey())) {
                PropertyUtils.setProperty(contact, entry.getKey(), entry.getValue());
            }
        } else {
            contact.put(entry.getKey(), entry.getValue());
        }

    }

    ContactsController.instance().save(contact);

    submission.setEverCookie(contact.getEverCookie()).setContactId(contact.getId()).setSubmittedAt(mils());
    FormSubmissionController.instance().save(submission);

    FormSubmissionEmailTaskHandler.enqueue(submission);

    return true;
}

From source file:com.wso2telco.gsma.authenticators.extension.CustomRequestCoordinator.java

/**
 * Handles the initial request (from the calling servlet)
 *
 * @param request  request//from  w  w w . j  a va 2 s.c  om
 * @param response response
 * @throws FrameworkException throws when error occurred from framework
 */
protected AuthenticationContext initializeFlow(HttpServletRequest request, HttpServletResponse response)
        throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Initializing the flow");
    }

    // "sessionDataKey" - calling servlet maintains its state information
    // using this
    String callerSessionDataKey = request.getParameter(FrameworkConstants.SESSION_DATA_KEY);

    // "commonAuthCallerPath" - path of the calling servlet. This is the url
    // response should be sent to
    String callerPath = getCallerPath(request);

    // "type" - type of the request. e.g. samlsso, openid, oauth, passivests
    String requestType = request.getParameter(FrameworkConstants.RequestParams.TYPE);

    // "relyingParty"
    String relyingParty = request.getParameter(FrameworkConstants.RequestParams.ISSUER);

    // tenant domain
    String tenantDomain = getTenantDomain(request);

    // Store the request data sent by the caller
    AuthenticationContext context = new AuthenticationContext();
    context.setCallerSessionKey(callerSessionDataKey);
    context.setCallerPath(callerPath);
    context.setRequestType(requestType);
    context.setRelyingParty(relyingParty);
    context.setTenantDomain(tenantDomain);

    // generate a new key to hold the context data object
    String contextId = UUIDGenerator.generateUUID();
    context.setContextIdentifier(contextId);

    if (log.isDebugEnabled()) {
        log.debug("Framework contextId: " + contextId);
    }

    // if this a logout request from the calling servlet
    if (request.getParameter(FrameworkConstants.RequestParams.LOGOUT) != null) {

        if (log.isDebugEnabled()) {
            log.debug("Starting a logout flow");
        }

        context.setLogoutRequest(true);

        if (context.getRelyingParty() == null || context.getRelyingParty().trim().length() == 0) {

            if (log.isDebugEnabled()) {
                log.debug("relyingParty param is null. This is a possible logout scenario.");
            }

            Cookie cookie = FrameworkUtils.getAuthCookie(request);

            if (cookie != null) {
                context.setSessionIdentifier(cookie.getValue());
            }

            return context;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Starting an authentication flow");
        }
    }

    findPreviousAuthenticatedSession(request, context);
    buildOutboundQueryString(request, context);

    return context;
}

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

/** {@inheritDoc} */
@Override/*from   w  ww .  ja  va  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: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 ww w.  j a  v  a  2s.  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:org.apache.archiva.redback.integration.util.AutoLoginCookies.java

public AuthenticationKey getRememberMeKey(HttpServletResponse httpServletResponse,
        HttpServletRequest httpServletRequest) {
    if (!isRememberMeEnabled()) {
        return null;
    }//from ww  w.j  av a  2  s . c  o  m

    Cookie rememberMeCookie = getCookie(httpServletRequest, REMEMBER_ME_KEY);

    if (rememberMeCookie == null) {
        log.debug("Remember Me Cookie Not Found: {}", REMEMBER_ME_KEY);
        return null;
    }

    // Found user with a remember me key.
    String providedKey = rememberMeCookie.getValue();

    log.debug("Found remember me cookie : {}", providedKey);

    CookieSettings settings = securitySystem.getPolicy().getRememberMeCookieSettings();
    return findAuthKey(REMEMBER_ME_KEY, providedKey, settings.getDomain(), settings.getPath(),
            httpServletResponse, httpServletRequest);
}

From source file:shiver.me.timbers.spring.security.jwt.AuthenticationRequestJwtTokenParserTest.java

@Test
@SuppressWarnings("unchecked")
public void Can_parse_a_jwt_token_from_a_cookie() throws JwtInvalidTokenException {

    final HttpServletRequest request = mock(HttpServletRequest.class);

    final Cookie cookie = mock(Cookie.class);
    final String token = someString();
    final Object principal = new Object();
    final Authentication expected = mock(Authentication.class);

    // Given/*from  w w  w .  j  a v  a  2 s  . c  o  m*/
    given(request.getCookies()).willReturn(new Cookie[] { mock(Cookie.class), cookie, mock(Cookie.class) });
    given(cookie.getName()).willReturn(tokenName);
    given(cookie.getValue()).willReturn(token);
    given(principleTokenParser.parse(token)).willReturn(principal);
    given(authenticationConverter.convert(principal)).willReturn(expected);

    // When
    final Authentication actual = tokenParser.parse(request);

    // Then
    assertThat(actual, is(expected));
}

From source file:com.bilko.controller.BlogController.java

private String getSessionCookie(final Request request) {
    final Cookie[] cookies = request.raw().getCookies();
    if (cookies == null) {
        return null;
    }//ww  w.  j  a v  a2 s  . co  m
    for (final Cookie cookie : cookies) {
        if (cookie.getName().equals("session")) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java

@Override
public String getPortalSessionId(final HttpServletRequest request) {
    String portalSessionId = null;

    // Put sessionId in current Http request
    final Object attrValue = request.getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    if (attrValue != null && attrValue instanceof String) {
        portalSessionId = (String) attrValue;
    }//  w  w w  . j a va 2 s  .c om

    if (!StringUtils.hasText(portalSessionId)) {
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (cookie != null && IPortal.PORTAL_SESSION_ID_COOKIE_NAME.equals(cookie.getName())) {
                    portalSessionId = cookie.getValue();
                }
            }
        }
    }

    if (!StringUtils.hasText(portalSessionId)) {
        // Search Portal Session Id in Http Session
        portalSessionId = (String) request.getSession(true).getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    }

    if (!StringUtils.hasText(portalSessionId)) {
        // Search Portal Session Id in Http Request params
        portalSessionId = request.getParameter(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    }

    // Null is the default value
    if (!StringUtils.hasText(portalSessionId) || !this.sessionBucketCache.containsKey(portalSessionId)) {
        // If the session Id cannot be found in the cache we cannot trust the session Id found.
        portalSessionId = null;
    }

    return portalSessionId;
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchWithinDate(HttpServletRequest request, HttpServletResponse response) {
    Cookie sbtCookie = null;

    String searchWithinDate = request.getParameter("searchWithinDate");
    if (searchWithinDate == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchWithinDate")) {
                sbtCookie = c;//from   w  w w .  j  av  a2 s  . com
            }
        }
        if (sbtCookie != null) {
            searchWithinDate = sbtCookie.getValue();
        } else {
            searchWithinDate = "true";
        }
    } else {
        sbtCookie = new Cookie("searchWithinDate", searchWithinDate);
        sbtCookie.setPath("/");
        response.addCookie(sbtCookie);
    }
    return searchWithinDate;
}