Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.jaspersoft.jasperserver.war.control.JSCommonController.java

protected void setupLoginPage(HttpServletRequest req) {
    Cookie[] cookies = req.getCookies();
    String locale = null;/*from  w w w .ja va 2 s . c  o  m*/
    String preferredTz = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals(JasperServerConstImpl.getUserLocaleSessionAttr()))
                locale = cookie.getValue();
            if (cookie.getName().equals(JasperServerConstImpl.getUserTimezoneSessionAttr()))
                preferredTz = cookie.getValue();
        }
    }

    Locale displayLocale = req.getLocale();
    String preferredLocale;
    if (locale == null || locale.length() == 0) {
        preferredLocale = displayLocale.toString();
    } else {
        preferredLocale = locale;
    }

    if (preferredTz == null) {
        preferredTz = timezones.getDefaultTimeZoneID();
    }

    req.setAttribute("preferredLocale", preferredLocale);
    req.setAttribute("userLocales", locales.getUserLocales(displayLocale));
    req.setAttribute("preferredTimezone", preferredTz);
    req.setAttribute("userTimezones", timezones.getTimeZones(displayLocale));
    try {
        if (Integer.parseInt(passwordExpirationInDays) > 0) {
            allowUserPasswordChange = "true";
        }
    } catch (NumberFormatException e) {
        // if the value is NaN, then assume it's non postive.
        // not overwrite allowUserPasswordChange
    }
    req.setAttribute("allowUserPasswordChange", allowUserPasswordChange);
    req.setAttribute("passwordExpirationInDays", passwordExpirationInDays);
    req.setAttribute("passwordPattern", userAuthService.getAllowedPasswordPattern().replace("\\", "\\\\"));
    req.setAttribute("autoCompleteLoginForm", autoCompleteLoginForm);
    req.setAttribute(IS_DEVELOPMENT_ENVIRONMENT_TYPE, false);
    req.setAttribute(USERS_EXCEEDED, false);
    req.setAttribute(BAN_USER, false);
    req.setAttribute("isEncryptionOn", SecurityConfiguration.isEncryptionOn());
}

From source file:de.sainth.recipe.backend.security.AuthFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    String header = request.getHeader("Authorization");
    Optional<Cookie> cookie;
    if (request.getCookies() != null) {
        cookie = Arrays.stream(request.getCookies()).filter(c -> COOKIE_NAME.equals(c.getName())).findFirst();
    } else {//from  w  ww  .j  av  a2 s.  co m
        cookie = Optional.empty();
    }
    if (!cookie.isPresent() && (header == null || header.length() == 0)) {
        throw new AccessDeniedException("No authentication information present");
    }
    RecipeManagerAuthenticationToken authentication;
    try {
        if (cookie.isPresent()) {
            authentication = parseToken(cookie.get().getValue());
        } else {
            Optional<RecipeManagerAuthenticationToken> maybeAuthentication;
            if (header.startsWith("Bearer ")) {
                maybeAuthentication = parseBearerToken(header);
            } else {
                maybeAuthentication = parseBasicAuth(header);
            }
            if (maybeAuthentication.isPresent()) {
                authentication = maybeAuthentication.get();
            } else {
                throw new AccessDeniedException("Bad credentials");
            }
        }
    } catch (ExpiredJwtException | SignatureException e) {
        throw new AccessDeniedException("Token not valid");
    }
    SecurityContextHolder.getContext().setAuthentication(authentication);
    response.addCookie(createCookie(authentication, request.isSecure()));

    chain.doFilter(request, response);
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

private String getCookieHashs(HttpServletRequest httpRequest) {
    Cookie cookies[] = httpRequest.getCookies();
    if (cookies == null) {
        return "";
    }/* w  w w. j a  v a  2s .c om*/
    StringBuffer ret = new StringBuffer();
    for (Cookie cookie : cookies) {
        ret.append(cookie.getName().hashCode());
        ret.append(";");
        ret.append(cookie.getValue().hashCode());
        ret.append(";");
    }
    return ret.toString();
}

From source file:org.guanxi.idp.service.Logout.java

/**
 * Does the logging out. The method looks for the user's IdP cookie in the
 * request and if it finds it, it extracts the corresponding GuanxiPrincipal
 * and sends it to SSO.logout() for processing.
 * /*from w  w w .  ja  va  2  s .co  m*/
 * @param request
 *          Standard HttpServletRequest
 * @param response
 *          Standard HttpServletRequest
 * @throws ServletException
 *           if an error occurrs
 * @throws IOException
 *           if an error occurrs
 */
public void processLogout(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String cookieName = getCookieName();
    boolean loggedOut = false;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context...
                GuanxiPrincipal principal = (GuanxiPrincipal) servletContext
                        .getAttribute(cookies[c].getValue());

                // ...and get rid of it
                if (principal != null) {
                    servletContext.setAttribute(principal.getUniqueId(), null);
                }

                loggedOut = true;
            }
        }
    }

    /*
     * Only display the logout page if we're not in passive mode. What this
     * means is if we're in passive mode (passive = yes) then we're most likely
     * embedded in an application, which has it's own logout page.
     */
    if (!passive) {
        if (loggedOut)
            request.setAttribute("LOGOUT_MESSAGE",
                    messageSource.getMessage("idp.logout.successful", null, request.getLocale()));
        else
            request.setAttribute("LOGOUT_MESSAGE",
                    messageSource.getMessage("idp.logout.unsuccessful", null, request.getLocale()));

        request.getRequestDispatcher(logoutPage).forward(request, response);
    }
}

From source file:org.apache.hadoop.security.authentication.server.JWTRedirectAuthenticationHandler.java

/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request.// w  ww.  j  a  v a  2 s. c  om
 *
 * @param req servlet request to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
    String serializedJWT = null;
    Cookie[] cookies = req.getCookies();
    String userName = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                LOG.info(cookieName + " cookie has been found and is being processed");
                serializedJWT = cookie.getValue();
                break;
            }
        }
    }
    return serializedJWT;
}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;/*from   w  w  w . j av  a 2s.c o  m*/
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

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 ww .java  2s . 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:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request./* ww  w  . j  a v  a  2  s  . c  o m*/
 *
 * @param req servlet request to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
    String serializedJWT = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                LOG.info(cookieName + " cookie has been found and is being processed");
                serializedJWT = cookie.getValue();
                break;
            }
        }
    }
    return serializedJWT;
}

From source file:com.tenduke.example.scribeoauth.SessionManager.java

/**
 * Validates an authenticated session and will provide the logged in user's session information as validation result.
 * @param request Client HTTP request./*from  w w  w  .  jav  a  2s. com*/
 * @param response HTTP response.
 * @return Session information or null if session is not valid.
 */
public SessionInformation validateSession(final HttpServletRequest request,
        final HttpServletResponse response) {
    //
    SessionInformation retValue = null;
    //
    String sessionId = null;
    final Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        //
        for (Cookie cookie : cookies) {
            //
            if (SIGNED_SESSION_COOKIE_NAME.equals(cookie.getName())) {
                //
                sessionId = cookie.getValue().split("_")[0];
            }
        }
    }
    //
    if (sessionId != null) {
        //
        retValue = getSessionInformation(sessionId);
    }
    //
    return retValue;
}

From source file:com.adito.core.CoreUtil.java

/**
 * Get a cookie object from a request given its name. <code>null</code>
 * will be returned if the cookie cannot be found
 * /*from www.j a  v a  2 s.  c o m*/
 * @param name cookie name
 * @param request request.
 * @return cookie object
 */
public static Cookie getCookie(String name, HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(name)) {
                return cookies[i];
            }
        }
    }
    return null;
}