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.spshop.web.ShoppingController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login2(Model model, HttpServletRequest request, HttpServletResponse response) {

    User user = retrieveUserNameAndPWDFromCookie(request.getCookies());
    /*//from   ww w.j  a v a  2s  .co  m
    if(user!=null){
       model.addAttribute(LOGIN_USER_NAME,user.getEmail());
       model.addAttribute(LOGIN_PWD,user.getPassword());
    }*/

    return "login";

}

From source file:org.slc.sli.dashboard.web.interceptor.SessionCheckInterceptor.java

/**
 * Prehandle performs a session check on all incoming requests to ensure a user with an active spring security session,
 *  is still authenticated against the api.
 */// w  w  w.ja v  a2 s  .  co  m
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = SecurityUtil.getToken();

    JsonObject json = restClient.sessionCheck(token);

    // If the user is not authenticated, expire the cookie and set oauth_token to null
    if (!json.get(Constants.ATTR_AUTHENTICATED).getAsBoolean()) {
        SecurityContextHolder.getContext().setAuthentication(null);
        HttpSession session = request.getSession();
        session.setAttribute(SLIAuthenticationEntryPoint.OAUTH_TOKEN, null);
        for (Cookie c : request.getCookies()) {
            if (c.getName().equals(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE)) {
                c.setMaxAge(0);
            }
        }

        // Only redirect if not error page
        if (!(request.getServletPath().equalsIgnoreCase(ErrorController.EXCEPTION_URL)
                || request.getServletPath().equalsIgnoreCase(ErrorController.TEST_EXCEPTION_URL))) {
            response.sendRedirect(request.getRequestURI());
            return false;
        }
    }

    return true;
}

From source file:com.google.ie.web.controller.UserController.java

/**
 * Delete all the cookies related to the user from the system
 * //from  w ww .  j  ava2  s. c  o  m
 * @param request {@link HttpServletRequest} object
 * @param response {@link HttpServletResponse} object
 */
private void removeCookieFromSystem(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            // Don't remove access token cookie
            if (!StringUtils.equals(cookie.getName(), AuthenticationFilter.ACCESS_TOKEN)) {
                /* Set the max age to zero so that the cookie is deleted */
                cookie.setMaxAge(WebConstants.ZERO);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("The age of the cookies related to the "
                + "user has been set to zero and the cookies set into the response");
    }

}

From source file:org.apache.metron.rest.config.KnoxSSOAuthenticationFilterTest.java

@Test
public void getJWTFromCookieShouldProperlyReturnToken() {
    KnoxSSOAuthenticationFilter knoxSSOAuthenticationFilter = spy(new KnoxSSOAuthenticationFilter(
            "userSearchBase", mock(Path.class), "knoxKeyString", "knoxCookie", mock(LdapTemplate.class)));

    HttpServletRequest request = mock(HttpServletRequest.class);

    {/*from w  w w.  java 2  s.  c  o m*/
        // Should be null if cookies are empty
        assertNull(knoxSSOAuthenticationFilter.getJWTFromCookie(request));
    }
    {
        // Should be null if Knox cookie is missing
        Cookie cookie = new Cookie("someCookie", "someValue");
        when(request.getCookies()).thenReturn(new Cookie[] { cookie });

        assertNull(knoxSSOAuthenticationFilter.getJWTFromCookie(request));
    }
    {
        // Should return token from knoxCookie
        Cookie cookie = new Cookie("knoxCookie", "token");
        when(request.getCookies()).thenReturn(new Cookie[] { cookie });

        assertEquals("token", knoxSSOAuthenticationFilter.getJWTFromCookie(request));
    }

}

From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java

/**
 * Add request cookies to the attributes map
 *
 * @param httpServletRequest Http Servlet Request
 * @param attributes Map of attributes to add additional attributes to from the Http Request
 *///from w  ww  . j a va 2s.  c o m
protected void addRequestCookies(final HttpServletRequest httpServletRequest,
        final Map<String, List<Object>> attributes) {
    final Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (final Cookie cookie : cookies) {
        final String cookieName = cookie.getName();
        if (this.cookieAttributeMapping.containsKey(cookieName)) {
            for (final String attributeName : this.cookieAttributeMapping.get(cookieName)) {
                attributes.put(attributeName, list(cookie.getValue()));
            }
        }
    }
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

private boolean checkCookiesForToken(HttpServletRequest request, HttpSession session) {
    boolean cookieFound = false;

    // If there is no oauth credential, and the user has a dashboard cookie, add cookie value as
    // oauth session attribute.
    if (session.getAttribute(OAUTH_TOKEN) == null) {
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {

            // Loop through cookies to find dashboard cookie
            for (Cookie c : cookies) {
                if (c.getName().equals(DASHBOARD_COOKIE)) {

                    // DE883. We need to decrypt the cookie value to authenticate the token.
                    String decryptedCookie = null;
                    try {
                        String s = URLDecoder.decode(c.getValue(), "UTF-8");
                        decryptedCookie = propDecryptor.decrypt(s);
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }/*from   ww  w  .ja  v  a2s. com*/
                    JsonObject json = restClient.sessionCheck(decryptedCookie);

                    // If user is not authenticated, expire the cookie, else set OAUTH_TOKEN to
                    // cookie value and continue
                    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
                    if ((authElement != null) && (!authElement.getAsBoolean())) {
                        c.setMaxAge(0);
                        LOG.info(LOG_MESSAGE_AUTH_EXPIRING_COOKIE, new Object[] { request.getRemoteAddr() });
                    } else {
                        cookieFound = true;
                        session.setAttribute(OAUTH_TOKEN, decryptedCookie);
                        LOG.info(LOG_MESSAGE_AUTH_USING_COOKIE, new Object[] { request.getRemoteAddr() });
                    }

                }
            }
        }
    }

    return cookieFound;
}

From source file:org.esgf.globusonline.GOFormView1Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request) {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");

    Map<String, Object> model = new HashMap<String, Object>();

    String myproxyServerStr = null;

    try {// w w  w.  jav a 2s .c  om
        //get the openid here from the cookie
        Cookie[] cookies = request.getCookies();
        String openId = "";
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("esgf.idp.cookie")) {
                openId = cookies[i].getValue();
            }
        }

        LOG.debug("Got User OpenID: " + openId);
        myproxyServerStr = Utils.resolveMyProxyViaOpenID(openId);
        LOG.debug("Using MyProxy Server: " + myproxyServerStr);

        ESGFProperties esgfProperties = new ESGFProperties();
        UserInfoDAO uid = new UserInfoDAO(esgfProperties);
        UserInfo userInfo = uid.getUserByOpenid(openId);
        String myproxyUserName = userInfo.getUserName();

        LOG.debug("Got MyProxy Username: " + myproxyUserName);
        //System.out.println("Got MyProxy Username: " + myproxyUserName);

        if (request.getParameter(GOFORMVIEW_MODEL) != null) {
            //it should never come here...
        } else {
            //place the dataset name, file names and urls into the model
            model.put(GOFORMVIEW_MYPROXY_SERVER, myproxyServerStr);
            model.put(GOFORMVIEW_SRC_MYPROXY_USER, myproxyUserName);
            model.put(GOFORMVIEW_FILE_URLS, file_urls);
            model.put(GOFORMVIEW_FILE_NAMES, file_names);
            model.put(GOFORMVIEW_DATASET_NAME, dataset_name);
        }
    } catch (YadisException ye) {
        String eMsg = ye.toString();
        if (eMsg.indexOf("0x702") != -1) {
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG,
                    "Please <a href=\"login\">Login</a>" + " before trying to download data!");
        } else {
            String errorMsg = "Failed to resolve OpenID: " + ye;
            LOG.error("Failed to resolve OpenID: " + ye);
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                    + " logged in as a valid user before trying to download data!<br><br>");
        }
    } catch (Exception e) {
        String errorMsg = "Failed to resolve OpenID: " + e;
        LOG.error("Failed to resolve OpenID: " + e);
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                + " logged in as a valid user before trying to download data!<br><br>");
    }
    return new ModelAndView("goformview1", model);
}

From source file:EditForm.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String photo_id = request.getQueryString();

    PrintWriter out = response.getWriter();

    // Check to makes sure the user is logged in
    String userid = "";
    Cookie login_cookie = null;//from www  .j a  va  2  s . co m
    Cookie cookie = null;
    Cookie[] cookies = null;
    // Get an array of cookies associated with this domain
    cookies = request.getCookies();
    // If any cookies were found, see if any of them contain a valid login.
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            // out.println(cookie.getName()+"<br>");
            // However, we only want one cookie, the one whose name matches
            // the
            // userid that has logged in on this browser.
            if (i != 0 && userid == "") {
                userid = cookie.getName();
            }
        }
    }
    // If no login was detected, redirect the user to the login page.
    if (userid == "") {
        out.println("<a href=login.jsp>Please login to access this site.</a>");
    }
    // Else, we have a valid session.
    else {

        out.println("<html><body><head><title>Edit Image</title></head><body ><P>");
        out.println("<form name=\"EditForm\" method=\"POST\" action=\"EditImage?" + photo_id + "\"><table>");
        out.println("<tr><td> Subject: <td> <input type=text size=20 name=subject>");
        out.println(
                "<tr><td alian = right>  Location: </td><td alian = left> <input type=text size=20 name=place></td></tr>");
        out.println("<tr><td alian = right>  Date: </td><td alian = left> <script type=\"text/javascript\""
                + " src=\"http://www.snaphost.com/jquery/Calendar.aspx?dateFormat=yy-mm-dd\"></script></script> &nbsp;</td></tr>");
        out.println(
                "<tr><td alian = right>  Description: </td><td alian = left> <textarea name=description rows=10 cols=30></textarea></td></tr>");

        out.println("<tr><td alain = right>     Who Can See This Photo:");
        out.println(
                "<td>Everyone <input class=\"everyone\" name = \"permission\" type=\"radio\" id=\"everyone\" value=\"everyone\">");
        out.println(
                "Only Me <input class=\"useronly\" name = \"permission\" type=\"radio\" id=\"useronly\" value=\"useronly\">");
        out.println(
                "Specific Group <input class=\"conditional_form_part_activator\" name = \"permission\" type=\"radio\" id=\"group\" value=\"group\">");

        out.println(
                "<div class=\"conditional_form_part\">Group Name: <input class=\"groupname\" type=text size=20 name=\"groupName\"></td></select> </div></tr></td>");

        out.println(
                "<tr><td alian = center colspan=\"2\"><input type = submit value = \"Update Image\"></td></tr></form></table></body></html>");
    }

}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private void fromSSO(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
    try {//from www  .ja  v a  2 s  .c  o m
        Cookie lcook = request.getCookies()[0];
        HashMap<String, String> attrs = validateCookie(lcook, "lcook");
        addAttributes(attrs, request.getSession());
        chain.doFilter(request, response);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServletException e) {
        e.printStackTrace();
    }
}