Example usage for javax.servlet.http Cookie Cookie

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

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:com.kingcore.framework.util.CookieUtils.java

/**
 *  ? domain clearCookie/*w w w.ja  v  a  2 s .  c  o m*/
 * clear a cookie from client side.
 * @param name the name of cookie will be cleared.
 * @param response HttpServletResponse Object.
 */
public static void clearCookie(String name, HttpServletResponse response) {
    Cookie cookie = new Cookie(name, null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
}

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

protected boolean auth(String spEntityID, HttpServletRequest request, HttpServletResponse response) {
    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    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
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }/*from  ww  w  .j a  v a 2 s  . c o  m*/
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                try {
                    request.getRequestDispatcher(errorPage).forward(request, response);
                } catch (Exception e) {
                    logger.error("Could not display authentication error page", e);
                }
                return false;
            }
        }
    } // if (request.getParameter("guanxi:mode") != null) {

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spEntityID))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    try {
        request.getRequestDispatcher(authPage).forward(request, response);
    } catch (Exception e) {
        logger.error("Could not display authentication page", e);
    }

    return false;
}

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  w w .  j  av a2 s .  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:fr.mby.opa.login.web.controller.LoginController.java

/**
 * @param model/* w  w  w  . j a  v a2 s  .c o  m*/
 * @param request
 */
protected void initView(final ModelMap model, final HttpServletRequest request,
        final HttpServletResponse response) {
    final IApp thisApp = this.portalService.getTargetedApp(request);
    model.addAttribute("app", thisApp);
    model.addAttribute("loginForm", new LoginForm());

    response.addCookie(new Cookie(IPortal.SIGNATURE_PARAM_NAME, thisApp.getSignature()));
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }/*  www  . jav  a  2 s .c om*/

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    String requestURI = httpReq.getRequestURI();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request path " + requestURI);
    }
    boolean authenticate = true;
    String user = null;
    if (getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (WEBAPP_PROXY_USER.equals(c.getName())) {
                    user = c.getValue();
                    break;
                }
            }
        }
        if (requestURI.equals(WebServices.PATH) && (user != null)) {
            String token = createClientToken(user, httpReq.getLocalAddr());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create token " + token);
            }
            Cookie cookie = new Cookie(CLIENT_COOKIE, token);
            httpResp.addCookie(cookie);
        }
        authenticate = false;
    }
    if (authenticate) {
        Cookie cookie = null;
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (c.getName().equals(CLIENT_COOKIE)) {
                    cookie = c;
                    break;
                }
            }
        }
        boolean valid = false;
        if (cookie != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying token " + cookie.getValue());
            }
            user = verifyClientToken(cookie.getValue());
            valid = true;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token valid");
            }
        }
        if (!valid) {
            httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    if (user == null) {
        LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final StramWSPrincipal principal = new StramWSPrincipal(user);
        ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.OAuthAction.java

/** ACTIONS **/
// http://localhost:8080/ciapl/external/oauth/userdialog&client_id=123123&redirect_uri=http://www.google.com

public ActionForward getUserPermission(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String clientId = request.getParameter("client_id");
    String redirectUrl = request.getParameter("redirect_uri");
    Person person = getLoggedPerson(request);

    if (!StringUtils.isEmpty(clientId) && !StringUtils.isEmpty(redirectUrl)) {
        if (person == null) {
            //redirect person to this action with client id in session

            final String cookieValue = clientId + "|" + redirectUrl;
            response.addCookie(/*from ww  w.ja v  a2s.c om*/
                    new Cookie(OAUTH_SESSION_KEY, Base64.getEncoder().encodeToString(cookieValue.getBytes())));
            if (CoreConfiguration.casConfig().isCasEnabled()) {
                response.sendRedirect(CoreConfiguration.casConfig().getCasLoginUrl(
                        CoreConfiguration.getConfiguration().applicationUrl() + "/oauth/userdialog"));
            } else {
                response.sendRedirect(request.getContextPath() + "/oauth/userdialog");
            }
            return null;
        } else {
            return redirectToRedirectUrl(mapping, request, response, person, clientId, redirectUrl);
        }
    } else {
        if (person != null) {
            // this is the request that will recover client id from session
            final Cookie cookie = CookieReaderUtils.getCookieForName(OAUTH_SESSION_KEY, request);
            if (cookie == null) {
                logger.debug("Cookie can't be null because this a direct request from this action with cookie");
                return mapping.findForward("oauthErrorPage");
            }
            final String sessionClientId = cookie.getValue();
            if (!StringUtils.isEmpty(sessionClientId)) {
                return redirectToRedirectUrl(mapping, request, response, person, cookie);
            }
        } else {
            logger.debug("Person should not be null since this a redirect from this action with cookie");
        }
    }

    return mapping.findForward("oauthErrorPage");

}

From source file:org.apache.cxf.fediz.service.idp.util.WebUtils.java

public static void addCookie(final RequestContext context, final String cookieName, final String cookieValue) {
    HttpServletResponse httpServletResponse = getHttpServletResponse(context);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setSecure(true);// w  w  w .  j a va2 s  .  c  om
    cookie.setMaxAge(-1);
    httpServletResponse.addCookie(cookie);
}

From source file:org.jasig.cas.web.flow.LogoutActionTests.java

@Test
public void testLogoutCookie() throws Exception {
    Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(new Cookie[] { cookie });
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FINISH_EVENT, event.getId());
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

@Override
public Cookie[] getCookies() {
    String cookieHeader = getHeaderCaseInsensitive(HttpHeaders.COOKIE);
    if (cookieHeader == null) {
        return new Cookie[0];
    }/* w w w  . j  av  a  2s. co m*/
    String[] cookies = cookieHeader.split(HEADER_VALUE_SEPARATOR);
    List<Cookie> output = new ArrayList<>();

    for (String curCookie : cookies) {
        String[] cookieKeyValue = curCookie.split(HEADER_KEY_VALUE_SEPARATOR);
        if (cookieKeyValue.length < 2) {
            continue;
        }
        output.add(new Cookie(cookieKeyValue[0].trim(), cookieKeyValue[1].trim()));
        // TODO: Parse the full cookie
    }
    Cookie[] returnValue = new Cookie[output.size()];
    return output.toArray(returnValue);
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testPersonUserCertLoginReopenBrowserWindow() throws Exception {
    Cookie cookie = new Cookie(SessionManager.getPersonUserCertificateLoggedOutCookieName(TENANT_NAME), "");
    assertErrorResponseUsingPersonUserCert(null, null, cookie,
            "access_denied: already logged in once on this browser session");
}