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:fr.gael.dhus.spring.security.handler.LoginSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {
    String name = authentication.getName();
    try {/*from   w  ww.j  a  va2  s .  c  om*/
        ValidityAuthentication auth = (ValidityAuthentication) authentication;

        name = EncryptPassword.encrypt(name, PasswordEncryption.MD5);
        Cookie authCookie = new Cookie(CookieKey.AUTHENTICATION_COOKIE_NAME, name);
        authCookie.setPath("/");
        authCookie.setHttpOnly(true);
        authCookie.setMaxAge(-1);

        String validity = auth.getValidity();
        //         Cookie validityCookie = new Cookie (CookieKey.VALIDITY_COOKIE_NAME,
        //             validity);
        //         validityCookie.setPath ("/");
        //         validityCookie.setHttpOnly (true);

        String integrity = EncryptPassword.encrypt(name + validity, PasswordEncryption.SHA1);
        Cookie integrityCookie = new Cookie(CookieKey.INTEGRITY_COOKIE_NAME, integrity);
        integrityCookie.setPath("/");
        integrityCookie.setHttpOnly(true);
        integrityCookie.setMaxAge(-1);

        response.addCookie(authCookie);
        //         response.addCookie (validityCookie);
        response.addCookie(integrityCookie);
        request.getSession().setAttribute("integrity", integrity);
        SecurityContextProvider.saveSecurityContext(integrity, SecurityContextHolder.getContext());
    } catch (Exception e) {
        LOGGER.warn("Authentication process failed ! No cookie was generated", e);
    }
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    try {//from  w  w  w.j av  a 2s . c  o  m
        String remoteAddress = request.getRemoteAddr();

        this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress);
        String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response,
                data, spep);
        PrintStream out = new PrintStream(response.getOutputStream());

        /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */
        Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled");
        autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT
        autoSubmit.setPath("/");
        response.addCookie(autoSubmit);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "text/html");

        out.print(document);

        out.close();

        this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress);
    } catch (IOException e) {
        throw new AuthenticationException("Unable to send response due to an I/O error.", e);
    }
}

From source file:controllers.LoginController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  www.j a  v  a2s .co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //User user = (User) request.getAttribute("user");
    //if (user != null) {
    // User has been already registered
    //response.sendRedirect(request.getContextPath() + "/home");
    //} else {
    // Login in user
    String email = request.getParameter("email"), password = request.getParameter("pass");

    JSONObject object = null;
    object = (JSONObject) ISConnector.validateLogin(email, password);
    if (object.containsKey("token")) {
        Cookie cookie = new Cookie("token", (String) object.get("token"));
        cookie.setPath("/");
        long expiredDate = -1;
        if (object.containsKey("expiry_date")) {
            expiredDate = (long) object.get("expiry_date") - new Timestamp(new Date().getTime()).getTime();
            expiredDate /= 1000;
            cookie.setMaxAge((int) expiredDate);
        }
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + "/home");
    } else if (object.containsKey("error")) {
        request.setAttribute("error", (String) object.get("error"));
        String error = (String) object.get("error");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(error);
            out.println("</body>");
            out.println("</html>");

        }
        //doGet(request, response);
    } else {
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(object);
            out.println("</body>");
            out.println("</html>");

        }
    }
    //}
}

From source file:com.sjc.cc.login.action.LoginAction.java

/**
 * CookieID/*from w w  w .jav  a  2  s .co m*/
 * 
 * @param userId
 */
private void setCloudUserIdCookie(Long userId) {
    HttpServletResponse response = ServletActionContext.getResponse();
    Cookie loginInfo = new Cookie(COOKIE_CC_USER_ID, userId + "");
    loginInfo.setMaxAge(-1);
    if (logger.isDebugEnabled()) {
        logger.debug("The Cookie Cloud is :" + loginInfo + "," + loginInfo.getValue());
    }
    response.addCookie(loginInfo);
}

From source file:com.codename1.corsproxy.CORSProxy.java

@Override
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {/*from ww  w .  jav a2 s .co m*/
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        //servletCookie.setSecure(cookie.getSecure());
        servletCookie.setSecure(false);
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:com.test.servlet.LoginController.java

@Override
public void setResponse(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    String email = getParam(RequestParam.email.toString());
    String password = getParam(RequestParam.password.toString());
    if (Utility.isStringEmpty(email)) {
        writer.print(/* www.j av a2 s.co m*/
                Utility.generalErrorMessage(ResponseCode.email_not_provided.toString(), "Email is required!"));
        return;
    }
    if (Utility.isStringEmpty(password)) {
        writer.print(Utility.generalErrorMessage(ResponseCode.password_not_provided.toString(),
                "Password is required!"));
        return;
    }

    DBUtility dbUtil = new DBUtility(servlet);
    User user = dbUtil.getUser(email, password);
    if (user != null) {
        HttpSession session = request.getSession();
        session.setAttribute("user_id", user.getId());
        String sessionKey = SessionGenerator.getInstance().nextSessionId();
        Cookie cookie = new Cookie("auth_key", sessionKey);
        cookie.setMaxAge(Constants.COOKIE_AGE);
        response.addCookie(cookie);

        dbUtil.insertSession(sessionKey, user.getId());

        JSONObject jResponse = new JSONObject();
        jResponse.put(JSONKey.status.toString(), 0);
        //jResponse.put(JSONKey.auth_key.toString(), sessionKey);
        jResponse.put(JSONKey.user_info.toString(), user.toJSONObject());

        writer.print(jResponse.toString());
    } else {
        writer.print(Utility.generalErrorMessage(ResponseCode.email_doesnt_exist.toString(),
                "Email address not found"));
    }
}

From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java

/**
 * This method is useful only for Cross-Domain (CD) authentication scenario when GateIn and OpenSSO are in different DNS domains and they can't share cookie.
 *
 * It performs://from ww w .  ja  va 2  s.co m
 * <li>Parse and validate message from OpenSSO CDCServlet.</li>
 * <li>Use ssoToken from parsed message and establish OpenSSO cookie iPlanetDirectoryPro</li>
 * <li>Redirects to InitiateLoginFilter but with cookie established. So in next request, we can perform agent validation against OpenSSO server</li>
 *
 * @param httpRequest
 * @param httpResponse
 * @return true if parameter LARES with message from CDC is present in HttpServletRequest
 * @throws IOException
 */
protected boolean tryMessageFromCDC(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException {
    String encodedCDCMessage = httpRequest.getParameter("LARES");

    if (encodedCDCMessage == null) {
        if (log.isTraceEnabled()) {
            log.trace("Message from CDC not found in this HttpServletRequest");
        }
        return false;
    }

    CDMessageContext messageContext = cdcMessageParser.parseMessage(encodedCDCMessage);
    if (log.isTraceEnabled()) {
        log.trace("Successfully parsed messageContext " + messageContext);
    }

    // Validate received messageContext
    validateCDMessageContext(httpRequest, messageContext);

    // Establish cookie with ssoToken
    String ssoToken = messageContext.getSsoToken();
    Cookie cookie = new Cookie(cookieName, "\"" + ssoToken + "\"");
    cookie.setPath(httpRequest.getContextPath());
    httpResponse.addCookie(cookie);
    if (log.isTraceEnabled()) {
        log.trace("Cookie " + cookieName + " with value " + ssoToken + " added to HttpResponse");
    }

    // Redirect again this request to be processed by OpenSSOAgent. Now we have cookie established
    String urlToRedirect = httpResponse.encodeRedirectURL(httpRequest.getRequestURI());
    httpResponse.sendRedirect(urlToRedirect);

    return true;
}

From source file:org.akaza.openclinica.control.MainMenuServlet.java

public String getTimeoutReturnToCookie(HttpServletRequest request, HttpServletResponse response) {
    String queryStr = "";
    if (ub == null || StringUtils.isEmpty(ub.getName()))
        return queryStr;

    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("bridgeTimeoutReturn-" + ub.getName())) {
            try {
                queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage());
            }// www.  ja  v  a 2 s.  co  m
            cookie.setValue(null);
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if (response != null)
                response.addCookie(cookie);
            break;
        }
    }
    return queryStr;
}

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

@RequestMapping(value = "/logout_redirect", method = RequestMethod.POST)
public void logoutUsingRedirect(HttpServletRequest request, HttpServletResponse response)
        throws OIDCClientException {
    SessionID sessionId = getSessionID(request);
    if (sessionId == null) {
        sendRedirect(response, rootUrl);
        return;//from  www  .jav  a 2  s  .  com
    }

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

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

    URI logoutRequestURI = client.buildLogoutRequestURI(URI.create(postLogoutRedirectUrl), tokens.getIDToken(),
            logoutState);

    response.addCookie(logoutSessionCookie());
    sendRedirect(response, logoutRequestURI);
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *///from www  . j  ava  2s.com
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = requestForwarder.cookieNamePrefix.get() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}