Example usage for javax.servlet.http Cookie setMaxAge

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

Introduction

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

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java

public XWikiUser checkAuth(XWikiContext context) throws XWikiException {
    Cookie cookie;

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie("XWIKINTLMAUTHINFO", context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }/*from  ww  w .j  a v  a2 s  .co m*/

        return null;
    }

    Principal principal = null;

    Cookie[] cookies = context.getRequest().getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
        }
    }

    cookie = getCookie("XWIKINTLMAUTHINFO", context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    String msg = context.getRequest().getHeader("Authorization");
    if (msg != null) {
        LOG.debug("Found NTLM Auth Cookie, this could be an IE6 bug (#831167)");
        if (msg.startsWith("NTLM ")) {
            LOG.debug("Removing principal because of NTLM header");
            principal = null;
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(null, null, context);
        if (principal == null) {
            LOG.debug("Can't get principal");
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKINTLMAUTHINFO", encuname);
        usernameCookie.setMaxAge(-1);
        usernameCookie.setPath("/");
        context.getResponse().addCookie(usernameCookie);

        user = new XWikiUser(principal.getName());
    } else {
        user = new XWikiUser(principal.getName().startsWith(context.getDatabase())
                ? principal.getName().substring(context.getDatabase().length() + 1)
                : principal.getName());
    }

    LOG.debug("XWikiUser=" + user);

    return user;
}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Removes a cookie from the call, so it will be deleted on the client.
 * @param c The cookie to delete./*from www.jav  a 2  s.c o  m*/
 * @throws WGException
 */
public void removeCookie(Cookie c) throws WGException {
    testResponseHeaderWritable();
    if (!c.isFromClient()) {
        throw new WGAServerException("The cookie does not originate from the client and cannot be removed");
    }
    c.setMaxAge(0);
    getJavaResponse().addCookie(c.toJavaCookie());
    fetchCookies().remove(c.getName());
}

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

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object.//from   ww  w.  j  a  v  a 2 s.  c  om
 * @param response the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
        boolean newToken = false;
        AuthenticationToken token = getToken(httpRequest);
        if (token == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} triggering authentication",
                        getRequestURL(httpRequest)));
            }
            token = authHandler.authenticate(httpRequest, httpResponse);
            if (token != null && token != AuthenticationToken.ANONYMOUS) {
                token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
            }
            newToken = true;
        }
        if (token != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Request {0} user {1} authenticated", getRequestURL(httpRequest),
                        token.getUserName()));
            }
            final AuthenticationToken authToken = token;
            httpRequest = new HttpServletRequestWrapper(httpRequest) {
                @Override
                public String getAuthType() {
                    return authToken.getType();
                }

                @Override
                public String getRemoteUser() {
                    return authToken.getUserName();
                }

                @Override
                public Principal getUserPrincipal() {
                    return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                }
            };
            if (newToken && token != AuthenticationToken.ANONYMOUS) {
                String signedToken = signer.sign(token.toString());
                Cookie cookie = createCookie(signedToken);
                httpResponse.addCookie(cookie);
            }
            filterChain.doFilter(httpRequest, httpResponse);
        }
    } catch (AuthenticationException ex) {
        if (!httpResponse.isCommitted()) {
            Cookie cookie = createCookie("");
            cookie.setMaxAge(0);
            httpResponse.addCookie(cookie);
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        }
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.PreviousProcessingFilter.java

/**
 * Actualiza el timeout de la cookie de OpenId
 * @param ServletRequest //from   w  ww .j  ava2s .  c  o  m
 * @param ServletResponse
 * @param nombreCookie
 * @throws IOException
*/
private void actualizaCookie(HttpServletRequest request, HttpServletResponse response, String nombreCookie)
        throws IOException {
    Cookie cookie = null;
    if (log.isDebugEnabled())
        log.debug("Se coge la cookie " + nombreCookie);
    cookie = getCookie(nombreCookie, request.getCookies());
    int caducidadCookie = (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID)))
            .intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookie.setMaxAge(caducidadCookie);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:final_exam.BlogController.java

private void initializeRoutes() throws IOException {

    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(BlogController.class, "/final_exam/freemarker");

    // this is the blog home page
    get("/", (request, response) -> {
        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

        List<Document> posts = blogPostDAO.findByDateDescending(10);
        SimpleHash root = new SimpleHash();

        root.put("myposts", posts);
        if (username != null) {
            root.put("username", username);
        }//from  w ww. ja v a  2s  .  c  o  m

        return new ModelAndView(root, "blog_template.ftl");
    }, new FreeMarkerEngine(configuration));

    // used to display actual blog post detail page
    get("/post/:permalink", (request, response) -> {
        String permalink = request.params(":permalink");

        System.out.println("/post: get " + permalink);

        Document post = blogPostDAO.findByPermalink(permalink);
        if (post == null) {
            response.redirect("/post_not_found");
        } else {
            // empty comment to hold new comment in form at bottom of blog entry detail page
            SimpleHash newComment = new SimpleHash();
            newComment.put("name", "");
            newComment.put("email", "");
            newComment.put("body", "");

            SimpleHash root = new SimpleHash();

            root.put("post", post);
            root.put("comment", newComment);

            return new ModelAndView(root, "entry_template.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // handle the signup post
    post("/signup", (request, response) -> {
        String email = request.queryParams("email");
        String username = request.queryParams("username");
        String password = request.queryParams("password");
        String verify = request.queryParams("verify");

        HashMap<String, String> root = new HashMap<String, String>();
        root.put("username", StringEscapeUtils.escapeHtml4(username));
        root.put("email", StringEscapeUtils.escapeHtml4(email));

        if (validateSignup(username, password, verify, email, root)) {
            // good user
            System.out.println("Signup: Creating user with: " + username + " " + password);
            if (!userDAO.addUser(username, password, email)) {
                // duplicate user
                root.put("username_error", "Username already in use, Please choose another");
                return new ModelAndView(root, "signup.ftl");
            } else {
                // good user, let's start a session
                String sessionID = sessionDAO.startSession(username);
                System.out.println("Session ID is" + sessionID);

                response.raw().addCookie(new Cookie("session", sessionID));
                response.redirect("/welcome");
            }
        } else {
            // bad signup
            System.out.println("User Registration did not validate");
            return new ModelAndView(root, "signup.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // present signup form for blog
    get("/signup", (request, response) -> {
        SimpleHash root = new SimpleHash();

        // initialize values for the form.
        root.put("username", "");
        root.put("password", "");
        root.put("email", "");
        root.put("password_error", "");
        root.put("username_error", "");
        root.put("email_error", "");
        root.put("verify_error", "");

        return new ModelAndView(root, "signup.ftl");
    }, new FreeMarkerEngine(configuration));

    // will present the form used to process new blog posts
    get("/newpost", (request, response) -> {
        // get cookie
        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

        if (username == null) {
            // looks like a bad request. user is not logged in
            response.redirect("/login");
        } else {
            SimpleHash root = new SimpleHash();
            root.put("username", username);

            return new ModelAndView(root, "newpost_template.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // handle the new post submission
    post("/newpost", (request, response) -> {

        String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
        String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
        String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));

        if (username == null) {
            response.redirect("/login"); // only logged in users can post to blog
        } else if (title.equals("") || post.equals("")) {
            // redisplay page with errors
            HashMap<String, String> root = new HashMap<String, String>();
            root.put("errors", "post must contain a title and blog entry.");
            root.put("subject", title);
            root.put("username", username);
            root.put("tags", tags);
            root.put("body", post);
            return new ModelAndView(root, "newpost_template.ftl");
        } else {
            // extract tags
            ArrayList<String> tagsArray = extractTags(tags);

            // substitute some <p> for the paragraph breaks
            post = post.replaceAll("\\r?\\n", "<p>");

            String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

            // now redirect to the blog permalink
            response.redirect("/post/" + permalink);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    get("/welcome", (request, response) -> {

        String cookie = getSessionCookie(request);
        String username = sessionDAO.findUserNameBySessionId(cookie);

        if (username == null) {
            System.out.println("welcome() can't identify the user, redirecting to signup");
            response.redirect("/signup");

        } else {
            SimpleHash root = new SimpleHash();

            root.put("username", username);

            return new ModelAndView(root, "welcome.ftl");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // process a new comment
    post("/newcomment", (request, response) -> {

        String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
        String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
        String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
        String permalink = request.queryParams("permalink");

        Document post = blogPostDAO.findByPermalink(permalink);
        if (post == null) {
            response.redirect("/post_not_found");
        }
        // check that comment is good
        else if (name.equals("") || body.equals("")) {
            // bounce this back to the user for correction
            SimpleHash root = new SimpleHash();
            SimpleHash comment = new SimpleHash();

            comment.put("name", name);
            comment.put("email", email);
            comment.put("body", body);
            root.put("comment", comment);
            root.put("post", post);
            root.put("errors", "Post must contain your name and an actual comment");

            return new ModelAndView(root, "entry_template.ftl");
        } else {
            blogPostDAO.addPostComment(name, email, body, permalink);
            response.redirect("/post/" + permalink);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // present the login page
    get("/login", (request, response) -> {
        SimpleHash root = new SimpleHash();

        root.put("username", "");
        root.put("login_error", "");

        return new ModelAndView(root, "login.ftl");

    }, new FreeMarkerEngine(configuration));

    // process output coming from login form. On success redirect folks to the welcome page
    // on failure, just return an error and let them try again.
    post("/login", (request, response) -> {

        String username = request.queryParams("username");
        String password = request.queryParams("password");

        System.out.println("Login: User submitted: " + username + "  " + password);

        Document user = userDAO.validateLogin(username, password);

        if (user != null) {

            // valid user, let's log them in
            String sessionID = sessionDAO.startSession(user.get("_id").toString());

            if (sessionID == null) {
                response.redirect("/internal_error");
            } else {
                // set the cookie for the user's browser
                response.raw().addCookie(new Cookie("session", sessionID));

                response.redirect("/welcome");
            }
        } else {
            SimpleHash root = new SimpleHash();

            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("password", "");
            root.put("login_error", "Invalid Login");
            return new ModelAndView(root, "login.ftl");
        }
        return null;

    }, new FreeMarkerEngine(configuration));

    // Show the posts filed under a certain tag
    get("/tag/:thetag", (request, response) -> {

        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        SimpleHash root = new SimpleHash();

        String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag"));
        List<Document> posts = blogPostDAO.findByTagDateDescending(tag);

        root.put("myposts", posts);
        if (username != null) {
            root.put("username", username);
        }

        return new ModelAndView(root, "blog_template.ftl");

    }, new FreeMarkerEngine(configuration));

    // will allow a user to click Like on a post
    post("/like", (request, response) -> {

        String permalink = request.queryParams("permalink");
        String commentOrdinalStr = request.queryParams("comment_ordinal");

        // look up the post in question

        int ordinal = Integer.parseInt(commentOrdinalStr);

        // TODO: check return or have checkSession throw
        String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request));
        Document post = blogPostDAO.findByPermalink(permalink);

        //  if post not found, redirect to post not found error
        if (post == null) {
            response.redirect("/post_not_found");
        } else {
            blogPostDAO.likePost(permalink, ordinal);

            response.redirect("/post/" + permalink);
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // tells the user that the URL is dead
    get("/post_not_found", (request, response) -> {
        SimpleHash root = new SimpleHash();
        return new ModelAndView(root, "post_not_found.ftl");
    }, new FreeMarkerEngine(configuration));

    // allows the user to logout of the blog
    get("/logout", (request, response) -> {

        String sessionID = getSessionCookie(request);

        if (sessionID == null) {
            // no session to end
            response.redirect("/login");
        } else {
            // deletes from session table
            sessionDAO.endSession(sessionID);

            // this should delete the cookie
            Cookie c = getSessionCookieActual(request);
            c.setMaxAge(0);

            response.raw().addCookie(c);

            response.redirect("/login");
        }
        return null;
    }, new FreeMarkerEngine(configuration));

    // used to process internal errors
    get("/internal_error", (request, response) -> {

        SimpleHash root = new SimpleHash();

        root.put("error", "System has encountered an error.");
        return new ModelAndView(root, "error_template.ftl");

    }, new FreeMarkerEngine(configuration));
}

From source file:MyServlet.UserController.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // processRequest(request, response);
    Object message;/*from   w ww  .  j  a  v a 2 s  . co  m*/
    Object userResetToken;
    String url = "/main.jsp";
    action = request.getParameter("action");
    System.out.println("action" + action);
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();
    User theUser = (User) session.getAttribute("theUser");
    writer.println("Inside get" + action);

    if (theUser != null) {
        //writer.println("Inside user");
        if (action.equals("about")) {
            url = "/aboutl.jsp";

        }
        if (action.equals("how")) {
            url = "/main.jsp";
        }
        if (action.equals("home")) {
            url = "/main.jsp";
        }
        if (action.equals("main")) {
            url = "/main.jsp";
        }
        if (action.equals("login")) {
            url = "/login.jsp";
        }
        if (action.equals("create")) {
            try {
                String currentTime = sdf.format(dt);
                String token = request.getParameter("token");
                String expiryTime = UserDB.getTime(token);
                Date date1 = sdf.parse(expiryTime);
                Date date2 = sdf.parse(currentTime);
                long differenceInMillis = date2.getTime() - date1.getTime();
                if (differenceInMillis < 3600000) {
                    request.setAttribute("token", token);
                    url = "/signup.jsp";
                }
            } catch (ParseException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        if (action.equals("activation")) {
            String currentTime = sdf.format(dt);
            String value;
            String userToken;
            String password;
            userToken = request.getParameter("activationcode");
            System.out.println("userToken if" + userToken);
            String expiryTime = UserDB.getTime(userToken);

            try {
                Date date1 = sdf.parse(expiryTime);
                Date date2 = sdf.parse(currentTime);

                long differenceInMillis = date2.getTime() - date1.getTime();
                if (differenceInMillis < 3600000) {
                    User user = UserDB.activateUser(userToken);

                    if (user != null) {
                        value = userPassword.get(user.getEmail());
                        session.setAttribute("theUser", user);
                        try {

                            password = hashAndSalt(value);
                            userDB.addUser(user, password, salt);
                            userDB.addUser(user);
                            userDB.deleteTemp(userToken);
                        } catch (NoSuchAlgorithmException ex) {
                            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        url = "/login.jsp";
                    } else {
                        url = "/signup.jsp";
                    }
                }

            } catch (ParseException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (action.equals("resetpassword")) {
            try {
                String token;
                String currentTime = sdf.format(dt);
                token = request.getParameter("token");
                System.out.println("userToken else" + token);
                String expiryTime = UserDB.getTime(token);
                Date date1 = sdf.parse(expiryTime);
                Date date2 = sdf.parse(currentTime);
                long differenceInMillis = date2.getTime() - date1.getTime();
                if (differenceInMillis < 3600000) {
                    User user = UserDB.activateUser(token);
                    if (user != null) {
                        request.setAttribute("user", user);
                        request.setAttribute("userResetToken", token);
                        url = "/resetpassword.jsp";
                    } else {
                        url = "/signup.jsp";
                    }

                } else {
                    message = "Token is expired!!";
                    request.setAttribute("message", message);
                    url = "/signup.jsp";
                }
                //url="/login.jsp";
            } catch (ParseException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    } else {
        if (action.equals("about")) {
            url = "/about.jsp";
        }
        if (action.equals("how")) {
            url = "/how.jsp";
        }
        if (action.equals("home")) {
            if (flag == 0) {

                int i = request.getServerPort();
                String port = String.valueOf(i);
                Cookie myCookie = new Cookie("HostName", request.getServerName());
                myCookie.setMaxAge(60 * 60 * 24 * 365);
                myCookie.setPath("/");
                response.addCookie(myCookie);
                Cookie cookiePort = new Cookie("Port", port);
                myCookie.setMaxAge(60 * 60 * 24 * 365);
                myCookie.setPath("/");
                response.addCookie(cookiePort);
            }
            url = "/home.jsp";
            flag++;
        }
        if (action.equals("main")) {
            url = "/login.jsp";
        }
        if (action.equals("login")) {

            url = "/login.jsp";
        }
        if (action.equals("activation")) {
            String currentTime = sdf.format(dt);
            String value;
            String userToken;
            String password;
            userToken = request.getParameter("activationcode");
            System.out.println("userToken else" + userToken);
            String expiryTime = UserDB.getTime(userToken);
            try {
                Date date1 = sdf.parse(expiryTime);
                Date date2 = sdf.parse(currentTime);

                long differenceInMillis = date2.getTime() - date1.getTime();
                if (differenceInMillis < 3600000) {
                    User user = UserDB.activateUser(userToken);

                    if (user != null) {
                        value = userPassword.get(user.getEmail());
                        session.setAttribute("theUser", user);
                        try {

                            password = hashAndSalt(value);
                            userDB.addUser(user, password, salt);
                            userDB.addUser(user);
                            userDB.deleteTemp(userToken);
                        } catch (NoSuchAlgorithmException ex) {
                            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        url = "/login.jsp";
                    } else {
                        url = "/signup.jsp";
                    }
                }

            } catch (ParseException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        if (action.equals("resetpassword")) {

            try {
                String token;
                String currentTime = sdf.format(dt);
                token = request.getParameter("token");
                System.out.println("userToken else" + token);
                String expiryTime = UserDB.getTime(token);
                Date date1 = sdf.parse(expiryTime);
                Date date2 = sdf.parse(currentTime);
                long differenceInMillis = date2.getTime() - date1.getTime();
                if (differenceInMillis < 3600000) {
                    User user = UserDB.activateUser(token);
                    if (user != null) {
                        request.setAttribute("user", user);
                        request.setAttribute("userResetToken", token);
                        url = "/resetpassword.jsp";
                    } else {
                        url = "/signup.jsp";
                    }

                } else {
                    message = "Token is expired!!";
                    request.setAttribute("message", message);
                    url = "/signup.jsp";
                }
                //url="/login.jsp";
            } catch (ParseException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
    getServletContext().getRequestDispatcher(url).forward(request, response);

}

From source file:com.spshop.web.ShoppingController.java

@RequestMapping(value = "/logout")
public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
    request.getSession().invalidate();//from  w  w w  . java 2 s. com
    model.addAttribute(LOGOUT_ACTION, Boolean.TRUE.toString());
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (COOKIE_ACCOUNT.equals(cookie.getName())) {
                cookie = new Cookie(COOKIE_ACCOUNT, EMPTY_STR);
                cookie.setPath("/");
                cookie.setMaxAge(30 * 24 * 60 * 60);
                response.addCookie(cookie);
            }
        }
    }
    return "redirect:" + getSiteView().getHost();
}

From source file:org.b3log.solo.util.Solos.java

/**
 * Gets the current logged-in user./*from w ww .j  a  v a 2 s  . c o  m*/
 *
 * @param request  the specified request
 * @param response the specified response
 * @return the current logged-in user, returns {@code null} if not found
 */
public static JSONObject getCurrentUser(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie[] cookies = request.getCookies();
    if (null == cookies || 0 == cookies.length) {
        return null;
    }

    final BeanManager beanManager = BeanManager.getInstance();
    final UserRepository userRepository = beanManager.getReference(UserRepository.class);
    try {
        for (int i = 0; i < cookies.length; i++) {
            final Cookie cookie = cookies[i];
            if (!COOKIE_NAME.equals(cookie.getName())) {
                continue;
            }

            final String value = Crypts.decryptByAES(cookie.getValue(), COOKIE_SECRET);
            final JSONObject cookieJSONObject = new JSONObject(value);

            final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
            if (StringUtils.isBlank(userId)) {
                break;
            }

            JSONObject user = userRepository.get(userId);
            if (null == user) {
                break;
            }

            final String userPassword = user.optString(User.USER_PASSWORD);
            final String token = cookieJSONObject.optString(Keys.TOKEN);
            final String hashPassword = StringUtils.substringBeforeLast(token, ":");
            if (userPassword.equals(hashPassword)) {
                login(user, response);

                return user;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.TRACE, "Parses cookie failed, clears the cookie [name=" + COOKIE_NAME + "]");

        final Cookie cookie = new Cookie(COOKIE_NAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return null;
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * Deletes all cookies that start with "gsa"
 * /*  w  w  w .  ja v a 2  s.  c  om*/
 * @param request HTTP request
 * @param response HTTP response
 */
public void deleteCookies(HttpServletRequest request, HttpServletResponse response) {

    // Retrieve cookies
    Cookie[] allCookies = request.getCookies();
    try {
        // Protection
        if (allCookies != null) {

            // Look for the authentication cookie
            for (int i = 0; i < allCookies.length; i++) {

                logger.debug("Cookie: " + allCookies[i].getName());

                //look for all the cookies start with "gsa" and delete them
                if ((allCookies[i].getName()).startsWith("gsa")) {

                    Cookie gsaCookie = new Cookie(allCookies[i].getName(), allCookies[i].getValue());

                    gsaCookie.setMaxAge(0);

                    response.addCookie(gsaCookie);

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("GSA cookie: [" + gsaCookie.getName() + " has been deleted ]");

                }

            }

        }
    } catch (Exception e) {
        logger.error("Error when deleting cookies: " + e.getMessage(), e);
    }
}

From source file:com.xwiki.authentication.trustedldap.TrustedLDAPAuthServiceImpl.java

public XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException {
    Cookie cookie;

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie("XWIKISSOAUTHINFO", context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }//  www  . j  av  a2s .c o m

        return null;
    }

    Principal principal = null;

    if (LOG.isDebugEnabled()) {
        Cookie[] cookies = context.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
            }
        }
    }

    cookie = getCookie("XWIKISSOAUTHINFO", context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(username, password, context);
        if (principal == null) {
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKISSOAUTHINFO", encuname);
        usernameCookie.setMaxAge(-1);
        usernameCookie.setPath("/");
        context.getResponse().addCookie(usernameCookie);

        user = new XWikiUser(principal.getName());
    } else {
        user = new XWikiUser(principal.getName().startsWith(context.getDatabase())
                ? principal.getName().substring(context.getDatabase().length() + 1)
                : principal.getName());
    }

    LOG.debug("XWikiUser=" + user);

    return user;
}