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:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

private String getCookieValor(HttpServletRequest request, String nombreCookie) {
    Cookie cookie = null;
    String valor = null;//from  w ww . j  a  v a 2  s . c om
    cookie = getCookie(nombreCookie, request.getCookies());
    valor = cookie.getValue();
    return valor;
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLoggedOut() throws Exception {
    asRoot();//from  w  w w .j  a v a2s. co m
    User user = getSystemTenant().getOwner();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    String view = controller.loggedout(user.getUuid(), map, session, response, request);
    Cookie cookie = response.getCookie("JforumSSO");
    Assert.assertEquals(cookie.getValue(), "");
    Assert.assertTrue(session.isInvalid());
    if (config.getAuthenticationService().compareToIgnoreCase("cas") == 0) {
        Assert.assertEquals("redirect:" + config.getCasLogoutUrl() + "?service="
                + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8"), view);
    } else {
        Assert.assertEquals("redirect:/j_spring_security_logout", view);
    }

}

From source file:com.wavemaker.tools.deployment.cloudfoundry.CloudFoundryDeploymentTarget.java

private AuthenticationToken getAuthenticationToken() {
    RuntimeAccess runtimeAccess = RuntimeAccess.getInstance();
    if (runtimeAccess == null) {
        return null;
    }//from   w ww.  j av  a  2 s.c o  m
    Cookie cookie = WebUtils.getCookie(runtimeAccess.getRequest(), "wavemaker_authentication_token");
    if (cookie == null || !StringUtils.hasLength(cookie.getValue())) {
        return null;
    }
    SharedSecret sharedSecret = this.propagation.getForSelf(false);
    if (sharedSecret == null) {
        return null;
    }
    AuthenticationToken authenticationToken = sharedSecret.decrypt(TransportToken.decode(cookie.getValue()));
    return authenticationToken;
}

From source file:com.acmeair.web.RESTCookieSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    try {//www. j a v  a2  s . c o m
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();
        // The following code is to ensure that OG is always set on the thread
        try {
            TransactionService txService = getTxService();
            if (txService != null)
                txService.prepareForTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // could do .startsWith for now, but plan to move LOGOUT to its own REST interface eventually
        if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH)) {
            // if logging in, let the request flow
            chain.doFilter(req, resp);
            return;
        }

        Cookie cookies[] = request.getCookies();
        Cookie sessionCookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
                    sessionCookie = c;
                }
                if (sessionCookie != null)
                    break;
            }
            String sessionId = "";
            if (sessionCookie != null) // We need both cookie to work
                sessionId = sessionCookie.getValue().trim();
            else {
                log.info("falling through with a sessionCookie break, but it was null");
            }
            // did this check as the logout currently sets the cookie value to "" instead of aging it out
            // see comment in LogingREST.java
            if (sessionId.equals("")) {
                log.info("sending SC_FORBIDDEN due to empty session cookie");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // Need the URLDecoder so that I can get @ not %40
            ValidateTokenCommand validateCommand = new ValidateTokenCommand(sessionId);
            CustomerSession cs = validateCommand.execute();
            if (cs != null) {
                request.setAttribute(LOGIN_USER, cs.getCustomerid());
                chain.doFilter(req, resp);
                return;
            } else {
                log.info("sending SC_FORBIDDEN due  to validateCommand returning null");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        // if we got here, we didn't detect the session cookie, so we need to return 403
        log.info("sending SC_FORBIDDEN due finding no sessionCookie");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.hangum.tadpole.login.core.dialog.LoginDialog.java

/**
 * initialize cookie data//ww  w.  j  a v a2  s . co m
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                Locale locale = Locale.forLanguageTag(cookie.getValue());
                comboLanguage.setText(locale.getDisplayLanguage(locale));
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 3)
                return;
        }
    }

    // ? ? .
    comboLanguage.select(0);
    changeUILocale(comboLanguage.getText());
}

From source file:com.companyname.filters.Oauth2ReAuthenticationFilter.java

public void performFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Oauth2 Re-Authentication filter starts.");

    HttpServletRequest request = (HttpServletRequest) req;

    Boolean authenticated = true;

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        logger.info("user needs to be re-authenticated via oauth2 token stored in cookies");

        logger.info("get access token cookie");
        Cookie accessTokenCookie = getCookie(request, getAccessTokenCookieName());
        logger.info("get refresh token cookie");
        Cookie refreshTokenCookie = getCookie(request, getRefreshTokenCookieName());

        String accessTokenValue = null;
        String refreshTokenValue = null;

        if (refreshTokenCookie != null) {
            refreshTokenValue = accessTokenCookie.getValue();
            logger.info("refresh token cookie is retrieved from cookie with value = " + refreshTokenValue);
        }//  w w w.j a v a 2  s.  c om

        if (accessTokenCookie != null) {
            accessTokenValue = accessTokenCookie.getValue();
            logger.info("access token cookie is retrieved from cookie with value = " + accessTokenValue);
        }

        if (accessTokenValue != null) {
            authentication = getAuthenticationFromAccessToken(accessTokenValue);
            logger.info("authentication object is obtained successfully via the access token");
        }

        if (authentication != null) {
            /**
            PlatAuthentication appAuthentication
                = (PlatAuthentication) authentication;
            PlatformTokens tokens = new PlatformTokens();
            tokens.setAccessToken(accessTokenValue);
            tokens.setRefreshToken(refreshTokenValue);
            appAuthentication.setTokens(tokens);
            SecurityContextHolder.getContext().setAuthentication(appAuthentication);
            * **/

            if (!authentication.isAuthenticated()) {
                logger.info("Although the authentication object is retrieved via the access token "
                        + " however, it's marked as not authenticated.");
            }

            SecurityContextHolder.getContext().setAuthentication(authentication);
            logger.info("security context is loaded with the user's authentication object");
        } else {
            authenticated = false;
            logger.info("Authentication failure, no authentication is loaded into the security context");
        }

    }

    if (authenticated) {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        for (String role : roles) {
            logger.info("role found: " + role);
        }

        if (roles.contains("ROLE_USER")) {
            logger.info("This user has role of ROLE_USER");
            request.getSession().setAttribute("myVale", "myvalue");
        }
        //chain.doFilter(req, res);
    } //else {            
      //HttpServletResponse response = (HttpServletResponse) res;
      //response.sendRedirect("http://localhost.drillmap.com:8080"); // hardcoded for now        
      //}

    chain.doFilter(req, res);

}

From source file:fragment.web.AuthenticationControllerTest.java

@SuppressWarnings("unchecked")
@Test/*from  w ww .  j  a va  2  s .  c o m*/
public void testLoggedOutWithSuffix() throws Exception {
    asRoot();
    Tenant defaultTenant = getDefaultTenant();
    defaultTenant.setUsernameSuffix("test");
    tenantService.save(defaultTenant);

    com.vmops.model.Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_username_duplicate_allowed);
    configuration.setValue("true");
    configurationService.update(configuration);

    User user = getSystemTenant().getOwner();
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    String view = controller.loggedout(user.getUuid(), map, session, response, request);
    Cookie cookie = response.getCookie("JforumSSO");
    Assert.assertEquals(cookie.getValue(), "");
    if (config.getAuthenticationService().compareToIgnoreCase("cas") == 0) {
        Assert.assertEquals("redirect:" + config.getCasLogoutUrl() + "?service="
                + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8"), view);
    } else {
        Assert.assertEquals("redirect:/j_spring_security_logout", view);
    }

    List<String> suffixList = (List<String>) map.get("suffixList");
    Assert.assertEquals(1, suffixList.size());

    defaultTenant = getDefaultTenant();
    defaultTenant.setUsernameSuffix(null);
    tenantService.save(defaultTenant);

}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;//  w w  w.  j ava 2s  .  com
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.britesnow.snow.web.RequestContext.java

public Map<String, String> getCookieMap() {
    if (cookieMap == null) {
        cookieMap = new HashMap<String, String>();
        Cookie[] cookies = getReq().getCookies();

        if (cookies != null) {
            for (Cookie c : cookies) {
                String value = c.getValue();
                try {
                    value = URLDecoder.decode(value, "UTF-8");
                } catch (Exception e) {
                    // YES, ignore for now. If failed, the raw value will be in the cookie.
                }/* www  .java2 s  .c o m*/
                cookieMap.put(c.getName(), value);
            }
        }
    }
    return cookieMap;
}

From source file:com.hangum.tadpole.application.start.dialog.login.LoginDialog.java

/**
 * initialize cookie data/*from ww w . j av  a 2  s.  c  o  m*/
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_PWD.equals(cookie.getName())) {
                textPasswd.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                comboLanguage.setText(cookie.getValue());
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 4)
                break;
        }
    }
}