Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

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

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:org.apache.catalina.authenticator.AuthenticatorBase.java

/**
 * Register an authenticated Principal and authentication type in our
 * request, in the current session (if there is one), and with our
 * SingleSignOn valve, if there is one.  Set the appropriate cookie
 * to be returned.//from w  w  w .j  av a 2 s  .  c  o  m
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are generating
 * @param principal The authenticated Principal to be registered
 * @param authType The authentication type to be registered
 * @param username Username used to authenticate (if any)
 * @param password Password used to authenticate (if any)
 */
protected void register(HttpRequest request, HttpResponse response, Principal principal, String authType,
        String username, String password) {

    if (log.isDebugEnabled())
        log.debug("Authenticated '" + principal.getName() + "' with type '" + authType + "'");

    // Cache the authentication information in our request
    request.setAuthType(authType);
    request.setUserPrincipal(principal);

    Session session = getSession(request, false);
    // Cache the authentication information in our session, if any
    if (cache) {
        if (session != null) {
            session.setAuthType(authType);
            session.setPrincipal(principal);
            if (username != null)
                session.setNote(Constants.SESS_USERNAME_NOTE, username);
            else
                session.removeNote(Constants.SESS_USERNAME_NOTE);
            if (password != null)
                session.setNote(Constants.SESS_PASSWORD_NOTE, password);
            else
                session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
    }

    // Construct a cookie to be returned to the client
    if (sso == null)
        return;

    // Only create a new SSO entry if the SSO did not already set a note
    // for an existing entry (as it would do with subsequent requests
    // for DIGEST and SSL authenticated contexts)
    String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
    if (ssoId == null) {
        // Construct a cookie to be returned to the client
        HttpServletResponse hres = (HttpServletResponse) response.getResponse();
        ssoId = generateSessionId();
        Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, ssoId);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        hres.addCookie(cookie);

        // Register this principal with our SSO valve
        sso.register(ssoId, principal, authType, username, password);
        request.setNote(Constants.REQ_SSOID_NOTE, ssoId);

    } else {
        // Update the SSO session with the latest authentication data
        sso.update(ssoId, principal, authType, username, password);
    }

    // Fix for Bug 10040
    // Always associate a session with a new SSO reqistration.
    // SSO entries are only removed from the SSO registry map when
    // associated sessions are destroyed; if a new SSO entry is created
    // above for this request and the user never revisits the context, the
    // SSO entry will never be cleared if we don't associate the session
    if (session == null)
        session = getSession(request, true);
    sso.associate(ssoId, session);

}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

@RequestMapping(value = "/logout_form_post", method = RequestMethod.POST)
public void logoutUsingFormPost(HttpServletRequest request, HttpServletResponse response)
        throws OIDCClientException {
    SessionID sessionId = getSessionID(request);
    if (sessionId == null) {
        sendRedirect(response, rootUrl);
        return;/*  w  ww.j  a v a 2s  .co  m*/
    }

    OIDCTokens tokens = this.sessionManager.remove(sessionId);
    assert tokens != null;

    State logoutState = new State();
    this.logoutRequestTracker.add(logoutState, tokens.getIDToken());

    String logoutRequestForm = client.buildLogoutRequestHtmlForm(URI.create(postLogoutRedirectUrl),
            tokens.getIDToken(), logoutState);

    response.addCookie(logoutSessionCookie());
    try {
        response.getWriter().write(logoutRequestForm);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.baifendian.swordfish.webserver.controller.LoginController.java

/**
 * @param name ??/* ww  w .  j a v  a2s . c  om*/
 * @param email  email
 * @param password ?
 * @param request ?
 * @param response ?
 */
@RequestMapping(value = "", method = { RequestMethod.POST, RequestMethod.GET })
public UserSessionDto login(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "password") String password, HttpServletRequest request,
        HttpServletResponse response) {
    logger.info("Login, user name: {}, email: {}, password: {}", name, email, "******");

    // 
    if (StringUtils.isEmpty(name) && StringUtils.isEmpty(email)) {
        throw new ParameterException("name or email");
    }

    // 
    if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(email)) {
        throw new ParameterException("name or email");
    }

    //  ip ?
    String ip = HttpUtil.getClientIpAddress(request);
    if (StringUtils.isEmpty(ip)) {
        throw new ParameterException("ip");
    }

    // ?????
    User user = userService.queryUser(name, email, password);

    if (user == null) {
        throw new UnAuthorizedException("User password error");
    }

    //  session
    UserSessionDto data = sessionService.createSession(user, ip);

    if (data == null) {
        throw new UnAuthorizedException("Create session error");
    }

    response.setStatus(HttpStatus.SC_OK);
    response.addCookie(new Cookie("sessionId", data.getSessionId()));

    return data;
}

From source file:gr.abiss.calipso.userDetails.util.SecurityUtil.java

/**
 * Writes a cookie to the response. In case of a blank value the method will 
 * set the max age to zero, effectively marking the cookie for immediate 
 * deletion by the client if the <code>allowClear</code> is true or throw an exception if false.
 * Blank value strings mark cookie deletion. If 
 * @param response//  w w w . j a  v  a  2  s .c om
 * @param cookieName
 * @param cookieValue
 * @param allowClear
 */
private static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
        String cookieValue, boolean allowClear, UserDetailsConfig userDetailsConfig) {
    if (StringUtils.isBlank(cookieValue) && !allowClear) {
        throw new RuntimeException(
                "Was given a blank cookie value but allowClear is false for cookie name: " + cookieName);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("addCookie, cookieName: " + cookieName + ", cookie value: " + cookieValue + ", domain: "
                + userDetailsConfig.getCookiesDomain() + ", secure: " + userDetailsConfig.isCookiesSecure()
                + ", http-only: " + userDetailsConfig.isCookiesHttpOnly() + ", path: "
                + userDetailsConfig.getCookiesContextPath());
    }
    Cookie cookie = new Cookie(cookieName, cookieValue);

    // set the cookie domain
    if (StringUtils.isNotBlank(userDetailsConfig.getCookiesDomain())) {
        cookie.setDomain('.' + userDetailsConfig.getCookiesDomain());
    }
    // maybe not a good idea unless you can trust the proxy
    //      else if (StringUtils.isNotBlank(request.getHeader("X-Forwarded-Host"))) {
    //         cookie.setDomain('.' + request.getHeader("X-Forwarded-Host"));
    //      }
    //      else{
    //         cookie.setDomain('.' + request.getLocalName());
    //         
    //      }
    // set the cookie path
    if (StringUtils.isNotBlank(userDetailsConfig.getCookiesContextPath())) {
        cookie.setPath(userDetailsConfig.getCookiesContextPath());
    }
    //      else {
    //         cookie.setPath("/");
    //      }

    cookie.setSecure(userDetailsConfig.isCookiesSecure());
    cookie.setHttpOnly(userDetailsConfig.isCookiesHttpOnly());

    if (StringUtils.isBlank(cookieValue)) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("addCookie, setting max-age to 0 to clear cookie: " + cookieName);
        }
        cookie.setMaxAge(0);
    }
    response.addCookie(cookie);
}

From source file:atd.backend.Login.java

/**
 * Vangt het POST request van de login.jsp en controlleerd deze met de
 * database//from   ww w .  j  a v a 2s . com
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = req.getParameter("username").toLowerCase();

    try {
        Class.forName("org.apache.commons.codec.digest.DigestUtils");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String pass = org.apache.commons.codec.digest.DigestUtils.sha256Hex(req.getParameter("password"));
    RequestDispatcher rd = null;

    if (UsersDAO.authUser(username, pass)
            || (username.equals(adminUser)) && req.getParameter("password").equals(adminPwd)) {
        // Controlleer of het filter een redirect gezet heeft
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }

        req.getSession().setAttribute("username", UsersDAO.searchUser(username));
        resp.addCookie(new Cookie("username", username));
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        LogDAO.setLog(req.getRemoteAddr(), currentTime, UsersDAO.searchUser(username), null);
        rd.forward(req, resp);
    } else if (KlantenDAO.authKlant(username, pass)) {
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }
        req.getSession().setAttribute("username", KlantenDAO.searchKlant(username));
        System.out.println("klant setten");

        resp.addCookie(new Cookie("username", username));

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);

        LogDAO.setLog(req.getRemoteAddr(), currentTime, null, KlantenDAO.searchKlant(username));
        rd.forward(req, resp);
    } else {
        rd = req.getRequestDispatcher("/login/login.jsp");
        req.setAttribute("error",
                "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> ongeldige inlog gegevens </div>");
        rd.forward(req, resp);
    }
}

From source file:com.exilant.exility.core.HtmlRequestHandler.java

/***
 * Carry out all rituals of logging the user out
 * //from   w w w . j av  a 2s. c om
 * @param req
 * @param resp
 */
private void doLogout(HttpServletRequest req, HttpServletResponse resp) {
    Cookie cookie = new Cookie(AP.loggedInUserFieldName, "");
    Date now = DateUtility.addDays(new Date(), -2);
    cookie.setMaxAge((int) now.getTime());
    resp.addCookie(cookie);
    req.getSession().invalidate();
    // this.removeGlobalDataFromSession(req);
}

From source file:com.vmware.demo.HomeController.java

@RequestMapping(value = "/sso", method = RequestMethod.POST)
public String generateRequest(HttpServletRequest request, HttpServletResponse response, Locale locale,
        Model model, String action, String SAMLResponse, String SAMLCertificate, String idpUri, String samlCert,
        String s, String i, String nameIdFormat, String consumeUrl) {
    String serviceProviderId = (String) request.getSession().getAttribute(ATTRIBUTE_SP_ID);

    // SETUP TEST
    if ("setup".equals(action)) {
        logger.info("Setup test");

        // Pass along the standard set
        model.addAttribute(ATTRIBUTE_IDP_ID, identityProviderId);
        model.addAttribute(ATTRIBUTE_SP_ID, serviceProviderId);
        model.addAttribute(ATTRIBUTE_IDP_URI, idpUri);
        model.addAttribute("nameIdFormat", DEFAULT_NAMEID_FORMAT);
        model.addAttribute("consumeUrl", idpUri + CONSUME_REQUEST);

        // Set in a cookie for next time you come back
        Cookie cookie = new Cookie(COOKIE_NAME, idpUri);
        response.addCookie(cookie);

        if (null != samlCert) {
            logger.info("Setup test using uploaded certificate.");
            try {
                if (StringUtils.isNotEmpty(samlCert)) {
                    samlCert = SamlUtils.convertToPemFormat(SamlUtils.parsePemCertificate(samlCert));
                } else {
                    model.addAttribute(ATTRIBUTE_ERROR_MSG,
                            "Saml certificate not provided, no validation will be done.");
                }/*from w  w  w.j a  va  2s. co m*/
            } catch (SamlException e) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG,
                        "Failed to parse certificate. " + e.getLocalizedMessage());
                model.addAttribute(ATTRIBUTE_ACTION, "setupcert");
                return "home";
            }
        } else {
            logger.info("Setup test using meta data url.");
            samlCert = SamlService.getInstance().loadSigningKeyFromMetaData(idpUri + METADATA_REQUEST);
            if (null == samlCert) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG, "Failed to contact service at " + idpUri
                        + ", please fetch and upload certificate manually.");
                model.addAttribute(ATTRIBUTE_ACTION, "setupcert");
                return "home";
            }
        }

        // Save to session
        if (!StringUtils.isEmpty(idpUri)) {
            request.getSession().setAttribute(ATTRIBUTE_IDP_URI, idpUri);
        }
        if (!StringUtils.isEmpty(samlCert)) {
            request.getSession().setAttribute(ATTRIBUTE_SAML_CERT, samlCert);
        }
        if (!StringUtils.isEmpty(s)) {
            request.getSession().setAttribute(ATTRIBUTE_SP_ID, s);
        }

        model.addAttribute(ATTRIBUTE_ACTION, "generaterequest");
    }

    // GENERATE SAML REQUEST
    if ("generaterequest".equals(action)) {
        logger.info("Generating authnRequest");

        String authnRequest = SamlService.getInstance().generateSAMLRequest(CONSUMER_URI, nameIdFormat);

        model.addAttribute("consumeUrl", consumeUrl);
        model.addAttribute(ATTRIBUTE_IDP_URI, idpUri);
        model.addAttribute(ATTRIBUTE_AUTHN_REQUEST, authnRequest);
        model.addAttribute(ATTRIBUTE_RELAY_STATE, RELAY_STATE);
        model.addAttribute(ATTRIBUTE_IDP_ID, null != i ? i : identityProviderId);
        model.addAttribute(ATTRIBUTE_SP_ID, null != s ? s : serviceProviderId);
        model.addAttribute(ATTRIBUTE_SAML_CERTIFICATE, SAMLCertificate);
        model.addAttribute(ATTRIBUTE_ACTION, "sendrequest");
    }

    // VALIDATE SAML RESPONSE
    if (null != SAMLResponse) {

        logger.info(SAMLResponse);
        String decodedResponse;
        String relayState;
        String target;
        try {
            samlCert = (String) request.getSession().getAttribute(ATTRIBUTE_SAML_CERT);
            relayState = (String) request.getParameter(ATTRIBUTE_RELAY_STATE);
            target = (String) request.getParameter(ATTRIBUTE_TARGET);
            model.addAttribute(ATTRIBUTE_RELAY_STATE, relayState);
            model.addAttribute(ATTRIBUTE_TARGET, target);

            List<IdentityProvider> identityProviders = organizationHandler.getAllIdentityProviders();
            if (null == samlCert) {
                decodedResponse = SamlService.getInstance().validateSAMLResponse(SAMLResponse,
                        identityProviders);
            } else {
                decodedResponse = SamlService.getInstance().validateSAMLResponse(SAMLResponse, samlCert);
            }

            if (StringUtils.isBlank(decodedResponse)) {
                model.addAttribute(ATTRIBUTE_ERROR_MSG, "Failed to validate SAML Response");
                model.addAttribute("SAMLResponse", decodedResponse);
            } else {
                model.addAttribute(ATTRIBUTE_SUCCESS_MSG, "SAML Response validated.");
                model.addAttribute("SAMLResponse", decodedResponse);
            }
        } catch (Exception e) {
            model.addAttribute("SAMLResponse", SAMLResponse);
            model.addAttribute(ATTRIBUTE_ERROR_MSG, e.getLocalizedMessage());
        }
    }

    return "home";
}

From source file:com.yahoo.yos.YahooFilter.java

private void redirectForAuthorization(OAuthAccessor accessor, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    try {// w  w w  .ja  v a  2  s.c o  m
        // get the request token
        List<OAuth.Parameter> callback = OAuth.newList(OAuth.OAUTH_CALLBACK, callbackUrl);
        //client.getRequestToken(accessor, null, callback);
        OAuthMessage message = client.getRequestTokenResponse(accessor, null, callback);
    } catch (URISyntaxException ex) {
        throw new ServletException(ex);
    } catch (OAuthException ex) {
        throw new ServletException(ex);
    }
    if (accessor.requestToken != null) {
        try {
            RequestToken rt = new RequestToken();
            rt.setKey(accessor.requestToken);
            rt.setSecret(accessor.tokenSecret);
            Cookie yosdk_rt = rt.getCookie();
            yosdk_rt.setMaxAge(600);
            response.addCookie(yosdk_rt);
        } catch (JSONException ex) {
            throw new ServletException(ex);
        }
    } else {
        throw new ServletException("Failed to create request token");
    }
    String redirectUrl = OAuth.addParameters(provider.userAuthorizationURL, "oauth_token",
            accessor.requestToken, "oauth_callback", callbackUrl);
    request.setAttribute("yahooRedirect", redirectUrl);
    response.sendRedirect(redirectUrl);
}

From source file:com.yahoo.yos.YahooFilter.java

private void accessTokenExpired(OAuthAccessor accessor, HttpServletRequest request,
        HttpServletResponse response, AccessToken accessToken, FilterChain filterChain)
        throws IOException, ServletException, JSONException, OAuthException, URISyntaxException {
    if (logger.isDebugEnabled()) {
        logger.debug("access token expired, attempting to renew");
    }//from  ww w.  j  av  a 2  s.c  om
    long now = System.currentTimeMillis() / 1000;
    if (accessToken.getHandleExpires() == -1 || (now < accessToken.getHandleExpires())) {
        RequestToken requestToken = new RequestToken();
        requestToken.setKey(accessToken.getKey());
        requestToken.setSessionHandle(accessToken.getSessionHandle());
        accessor.tokenSecret = accessToken.getSecret();
        AccessToken at = fetchAccessToken(accessor, requestToken, null);
        Cookie yosdk_at = at.getCookie();
        yosdk_at.setMaxAge(30 * 24 * 60 * 60);
        response.addCookie(yosdk_at);
        String appId = oauthConfig.getProperty("yos.appid");
        YahooSession yahooSession = new YahooSession(client, consumer, at, appId);
        request.setAttribute("yahooSession", yahooSession);
        filterChain.doFilter(request, response);
    } else {
        Cookie at = new Cookie("yosdk_at", "");
        at.setMaxAge(0);
        at.setMaxAge(0);
        response.addCookie(at);
        request.setAttribute("yahooSession", null);
        request.setAttribute("yahooRedirect", null);
        filterChain.doFilter(request, response);
        if (redirect) {
            redirectForAuthorization(accessor, request, response);
        }
    }
}

From source file:org.kievguide.controller.UserController.java

@RequestMapping(value = "/settingssave", method = RequestMethod.POST)
public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail,
        @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname,
        @RequestParam("email") String email, @RequestParam("password") String password,
        @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request)
        throws FileNotFoundException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    SecureRandom random = new SecureRandom();
    String photoname = new BigInteger(130, random).toString(32);
    Place place = new Place();

    User user = userService.searchUser(useremail);
    user.setFirstname(firstname);/*from w w w.  j  a  v  a 2s .  c o m*/
    user.setLastname(lastname);
    user.setPassword(password);
    user.setEmail(email);
    if (!file.isEmpty()) {
        String folder = request.getSession().getServletContext().getRealPath("");
        folder = folder.substring(0, 30);
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg")));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        user.setPhotosrc("img/" + photoname + ".jpg");
    }

    userService.addUser(user);
    Cookie userCookie = new Cookie("userstatus", user.getEmail());
    response.addCookie(userCookie);
    String userStatus = Util.userPanel(user.getEmail());
    modelAndView.addObject("userstatus", userStatus);
    return new ModelAndView("redirect:" + "firstrequest");
}