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:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java

/**
 * This method filters every incoming request.
 * If request contains cookie, it checks whether the cookie is valid.
 *    A. If request cookie is present and is valid, forwards the request 
 *          to next page./*from  w  w w .  j  a  v  a 2s  . c o m*/
 *    B. If cookie is not valid and request is not coming from ACS, this
 *          method redirects the request to ACS login page.
 * If request does not contain a cookie, but contains an ACS token,
 * this method, creates or updates cookie and 
 * forwards the request to landing page.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // capture ACS response
    String acsToken = httpServletRequest.getParameter("wresult");
    if (null != acsToken && acsToken.trim().length() == 0) {
        acsToken = null;
    }
    String isEncodedWresult = httpServletRequest.getParameter("isEncodedWresult");
    String decodedTokenString = null;
    if (null != acsToken && null != isEncodedWresult && isEncodedWresult.trim().equalsIgnoreCase("true")) {
        decodedTokenString = new String(URLDecoder.decode(acsToken, "UTF-8"));
        acsToken = decodedTokenString;
    }

    // by pass the url access validation validateInvitationCode
    if (httpServletRequest.getRequestURI().contains("/validateInvitationCode")) {
        request.getRequestDispatcher("/validateInvitationCode.htm").forward(httpServletRequest,
                httpServletResponse);
    } else {

        CloudNinjaUser cloudNinjaUser = null;

        boolean isValidCookiePresent = false;
        String cookieName = CloudNinjaConstants.AUTH_COOKIE_NAME;

        Cookie preExistentCookie = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);

        if (preExistentCookie != null && StringUtils.isNotBlank(preExistentCookie.getValue())) {
            isValidCookiePresent = AuthFilterUtils.checkValidityOfCookie(preExistentCookie);
        }

        if (isValidCookiePresent) {
            Cookie cookieToUse = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);

            // Add cookie userNames, etc to request attributes
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToNextPage(httpServletRequest, httpServletResponse, chain);
        } else if (!isValidCookiePresent && (acsToken == null)) {
            redirectToACSPage(httpServletRequest, httpServletResponse);
            return;
        } else if (acsToken != null) {

            acsToken = new String(acsToken.getBytes(), CloudNinjaConstants.UTF_8_FORMAT);
            boolean isValidCertificate = AuthFilterUtils.checkCertificateValidity(acsToken);
            if (!isValidCertificate) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            try {
                cloudNinjaUser = parseSAMLResponseAndCreateCNUser(acsToken);
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            String liveGuid = null;

            //  GUID is present and user is null it means that user is from windowsLiveId
            // and is login-in in for the first time so we need to ask for verification code
            if (cloudNinjaUser != null && cloudNinjaUser.getUser() == null) {
                liveGuid = cloudNinjaUser.getLiveGUID();
                cloudNinjaUser = null;
                forwardToVerificationPage(httpServletRequest, httpServletResponse, liveGuid, acsToken);
                return;
            }
            // if user is null and no GUID is present
            // redirect to ACS page

            if (null == cloudNinjaUser) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            Cookie cookieToUse;
            if (preExistentCookie == null) {
                cookieToUse = AuthFilterUtils.createNewCookieForACSAuthenticatedUser(cloudNinjaUser,
                        cookieName);
            } else {
                cookieToUse = AuthFilterUtils.updateExistingCookie(preExistentCookie, cloudNinjaUser);
            }
            cookieToUse.setMaxAge(getCookieMaxAge());
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToLandingPage(httpServletRequest, httpServletResponse, chain, cloudNinjaUser);
        }
    }
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

private void sendToLogin(HttpServletRequest request, HttpServletResponse response, String loginPath) {

    // delete any existing sessions first
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().startsWith("_shib")) {
                log.debug("clearing cookie " + cookies[i].getName());
                Cookie c = new Cookie(cookies[i].getName(), "");
                c.setSecure(true);//from   ww  w.  ja v  a2s. c o m
                c.setPath("/");
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }

    String rp = "";
    if (request.getPathInfo() != null)
        rp = request.getPathInfo();
    String rqs = "";
    if (request.getQueryString() != null)
        rqs = "?" + request.getQueryString();
    String red = browserRootPath + request.getServletPath() + loginPath + rp + rqs;
    log.debug("no user yet: redirect for login to " + red);
    try {
        response.sendRedirect(red);
    } catch (IOException e) {
        log.error("redirect: " + e);
    }
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

@RequestMapping(value = "/logout/**", method = RequestMethod.GET)
public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) {
    // clear cookies/*  w ww . ja  v a 2 s .c om*/
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            String ckName = cookies[i].getName();
            if (ckName.equals(loginCookie) || ckName.startsWith("_shib")) {
                log.debug("cookie to clear " + ckName);
                Cookie c = new Cookie(ckName, "void");
                c.setSecure(true);
                c.setPath("/");
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }
    /**
            try {
               log.debug("redirect to: " +  logoutUrl);
               response.sendRedirect(logoutUrl);
            } catch (IOException e) {
               log.error("redirect: " + e);
            }
            return emptyMV("configuration error");
     **/
    String view = "browser";
    Device currentDevice = DeviceUtils.getCurrentDevice(request);
    if (currentDevice != null && currentDevice.isMobile())
        view = "mobile";
    ModelAndView mv = new ModelAndView(view + "/chooser");
    mv.addObject("root", browserRootPath);
    mv.addObject("vers", request.getServletPath());
    mv.addObject("pagetype", "browser/loggedout");
    mv.addObject("pathextra", "");
    mv.addObject("uwloginpath", standardLoginPath);
    mv.addObject("googleloginpath", googleLoginPath);
    mv.addObject("incommonloginpath", incommonLoginPath);
    return (mv);
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Creates an authentication request, authenticates the user and, if
 * successful, returns the user's credentials.
 * //from   www  .  j av a  2s  . c  o  m
 * @param username
 *        The username of the user attempting to authenticate.
 * 
 * @param password
 *        The password of the user attempting to authenticate.
 * 
 * @param request
 *        The HTTP request object.
 * 
 * @param response
 *        The HTTP response object.
 * 
 * @return The authorization token.
 * 
 * @throws OmhException
 *         There was a problem with the request. This could be any of the
 *         sub-classes of {@link OmhException}.
 */
@RequestMapping(value = "auth", method = RequestMethod.POST)
public @ResponseBody String getAuthentication(
        @RequestParam(value = PARAM_AUTHENTICATION_USERNAME, required = true) final String username,
        @RequestParam(value = PARAM_AUTHENTICATION_PASSWORD, required = true) final String password,
        final HttpServletRequest request, final HttpServletResponse response) throws OmhException {

    // Create the authentication request from parameters.
    AuthenticationToken token = handleRequest(request, response, new AuthenticationRequest(username, password));

    // Add a cookie for the authentication token.
    Cookie cookie = new Cookie(PARAM_AUTHENTICATION_AUTH_TOKEN, token.getToken());
    // Set the expiration on the cookie.
    cookie.setMaxAge(new Long((token.getExpires() - System.currentTimeMillis()) / 1000).intValue());
    // Build the path without the "auth" part.
    String requestUri = request.getRequestURI();
    cookie.setPath(requestUri.substring(0, requestUri.length() - 5));
    // Make sure the cookie is only used with HTTPS.
    cookie.setSecure(true);
    // Add the cookie to the response.
    response.addCookie(cookie);

    // Return the token.
    return token.getToken();
}

From source file:org.asynchttpclient.test.EchoHandler.java

@Override
public void handle(String pathInContext, Request request, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) throws IOException, ServletException {

    LOGGER.debug("Echo received request {} on path {}", request, pathInContext);

    if (httpRequest.getHeader("X-HEAD") != null) {
        httpResponse.setContentLength(1);
    }//from  ww  w . j  a  v a2  s.c  o m

    if (httpRequest.getHeader("X-ISO") != null) {
        httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_ISO_8859_1_CHARSET);
    } else {
        httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET);
    }

    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        httpResponse.addHeader("Allow", "GET,HEAD,POST,OPTIONS,TRACE");
    }

    Enumeration<String> e = httpRequest.getHeaderNames();
    String headerName;
    while (e.hasMoreElements()) {
        headerName = e.nextElement();
        if (headerName.startsWith("LockThread")) {
            final int sleepTime = httpRequest.getIntHeader(headerName);
            try {
                Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000);
            } catch (InterruptedException ex) {
                //
            }
        }

        if (headerName.startsWith("X-redirect")) {
            httpResponse.sendRedirect(httpRequest.getHeader("X-redirect"));
            return;
        }
        httpResponse.addHeader("X-" + headerName, httpRequest.getHeader(headerName));
    }

    String pathInfo = httpRequest.getPathInfo();
    if (pathInfo != null)
        httpResponse.addHeader("X-pathInfo", pathInfo);

    String queryString = httpRequest.getQueryString();
    if (queryString != null)
        httpResponse.addHeader("X-queryString", queryString);

    httpResponse.addHeader("X-KEEP-ALIVE", httpRequest.getRemoteAddr() + ":" + httpRequest.getRemotePort());

    Cookie[] cs = httpRequest.getCookies();
    if (cs != null) {
        for (Cookie c : cs) {
            httpResponse.addCookie(c);
        }
    }

    Enumeration<String> i = httpRequest.getParameterNames();
    if (i.hasMoreElements()) {
        StringBuilder requestBody = new StringBuilder();
        while (i.hasMoreElements()) {
            headerName = i.nextElement();
            httpResponse.addHeader("X-" + headerName, httpRequest.getParameter(headerName));
            requestBody.append(headerName);
            requestBody.append("_");
        }

        if (requestBody.length() > 0) {
            String body = requestBody.toString();
            httpResponse.getOutputStream().write(body.getBytes());
        }
    }

    String requestBodyLength = httpRequest.getHeader("X-" + CONTENT_LENGTH);

    if (requestBodyLength != null) {
        byte[] requestBodyBytes = IOUtils.toByteArray(httpRequest.getInputStream());
        int total = requestBodyBytes.length;

        httpResponse.addIntHeader("X-" + CONTENT_LENGTH, total);
        String md5 = TestUtils.md5(requestBodyBytes, 0, total);
        httpResponse.addHeader(CONTENT_MD5.toString(), md5);

        httpResponse.getOutputStream().write(requestBodyBytes, 0, total);
    } else {
        int size = 16384;
        if (httpRequest.getContentLength() > 0) {
            size = httpRequest.getContentLength();
        }
        if (size > 0) {
            int read = 0;
            while (read > -1) {
                byte[] bytes = new byte[size];
                read = httpRequest.getInputStream().read(bytes);
                if (read > 0) {
                    httpResponse.getOutputStream().write(bytes, 0, read);
                }
            }
        }
    }

    request.setHandled(true);
    httpResponse.getOutputStream().flush();
    // FIXME don't always close, depends on the test, cf ReactiveStreamsTest
    httpResponse.getOutputStream().close();
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractManageResourceController.java

@RequestMapping(value = "/get_sso_cmd_string", method = RequestMethod.POST)
@ResponseBody//w w  w  . jav a 2  s.  c o  m
public Map<String, String> getSSOCmdString(@ModelAttribute("currentTenant") Tenant tenant,
        @RequestParam(value = "tenant", required = false) String tenantParam,
        @RequestParam(value = "serviceInstanceUUID", required = true) String serviceInstanceUUID, ModelMap map,
        HttpServletRequest request, HttpServletResponse response) {

    logger.debug("### In getSSOCmdString  start method (POST)...");
    SsoObject ssoObject = new SsoObject();
    Tenant userTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);
    Map<String, String> responseMap = new HashMap<String, String>();
    if (userTenant.getState() == Tenant.State.NEW) {
        responseMap.put("status", "fail");
        if ((Boolean) request.getAttribute("isSurrogatedTenant")) {
            responseMap.put("error_message",
                    messageSource.getMessage("message.user.no.billing", null, getSessionLocale(request)));
            responseMap.put("url", "/portal/portal/home");
        } else {
            responseMap.put("url", "/portal/portal/tenants/editcurrent");
        }
    } else {
        // if user logged in as root and try to access cloud resources under specific account then using the specific
        // account and account owner.
        SsoHandler ssoHandler = ((CloudConnector) connectorManagementService
                .getServiceInstance(serviceInstanceUUID)).getSSOHandler();
        if (ssoHandler != null) {
            if ((Boolean) request.getAttribute("isSurrogatedTenant")) {
                logger.trace("###SPI Calling SsoHandler.handleLogin(User) for user:" + userTenant.getOwner());
                ssoObject = ssoHandler.handleLogin(userTenant.getOwner());
                logger.trace("###SPI Called SsoHandler.handleLogin(User) for user:" + userTenant.getOwner());
            } else {
                logger.trace("###SPI Calling SsoHandler.handleLogin(User) for user:" + getCurrentUser());
                ssoObject = ssoHandler.handleLogin(getCurrentUser());
                logger.trace("###SPI Calling SsoHandler.handleLogin(User) for user:" + getCurrentUser());
            }
            if (ssoObject != null && ssoObject.getCookies().size() > 0) {
                for (Cookie cookie : ssoObject.getCookies()) {
                    response.addCookie(cookie);
                    logger.debug("Sending cookies:" + cookie.getName() + " domain:" + cookie.getDomain());
                }
            }
            responseMap.put("callback", ssoObject.getCallBack());
            responseMap.put("status", "success");
            responseMap.put("cmdString", ssoObject.getSsoString());
        } else {
            // if a connector is not implementing a ssoHandler, return success
            responseMap.put("status", "success");
        }
    }
    logger.debug("### getSSOCmdString method ending...(POST)");
    return responseMap;
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx)
        throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*  w w  w  . ja  v a2 s .  c o  m*/
    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setOpen(true);
    tsession.refresh(this.ctx, this);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);

    // TODO add global session timeout
    // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    // TODO add global open session name
    Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

    sessionCookie.setPath("/");
    sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
    sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
    sessionCookie.setMaxAge(-1);
    // TODO add secure?
    // sessionCookie.setSecure(app.getCookieConfig().isSecure());
    resp.addCookie(sessionCookie);

    sessions.put(id, tsession);

    return tsession;
}

From source file:flex.messaging.services.http.proxy.ResponseFilter.java

protected void copyCookiesFromEndpoint(ProxyContext context) {
    HttpServletResponse clientResponse = FlexContext.getHttpResponse();

    if (clientResponse != null) {
        Cookie[] cookies = context.getHttpClient().getState().getCookies();
        // We need to filter out the request cookies, we don't need to send back to the client
        Set requestCookies = context.getRequestCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (requestCookies != null && requestCookies.contains(cookies[i])
                    && cookies[i].getExpiryDate() == null) {
                // It means it is a request cookie and nothing changed, we need to skip it 
                continue;
            }/*from   ww w.  j  a v  a  2s .  c o  m*/
            // Process the cookie;
            String domain = cookies[i].getDomain();
            String path = cookies[i].getPath();
            String name = cookies[i].getName();
            String value = cookies[i].getValue();

            String clientName = ResponseUtil.getCookieName(context, path, name, domain);

            if (Log.isInfo()) {
                String str = "-- Cookie in response: domain = '" + domain + "', path = '" + path
                        + "', client name = '" + clientName + "', endpoint name = '" + name + "', value = '"
                        + value;
                Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug(str);
            }

            javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(clientName, value);

            Date expiry = cookies[i].getExpiryDate();
            if (expiry != null) {
                int maxAge = (int) ((expiry.getTime() - System.currentTimeMillis()) / 1000);
                cookie.setMaxAge(maxAge);
            }
            cookie.setSecure(cookies[i].getSecure());
            cookie.setPath("/");

            clientResponse.addCookie(cookie);
        }
    }
}

From source file:com.concursive.connect.web.modules.login.auth.session.SessionValidator.java

/**
 * Follow the current session validation schema and determine if there is a
 * valid session for the user. If there is a valid session, return the
 * <code>User</code> associated with that session, otherwise, return
 * <i>null</i>.//from w  w w .j a va2 s  .c  o  m
 *
 * @param request -
 *                The servlet request as provided by the
 *                <code>ControllerServlet</code>.
 * @return A valid <code>User</code> upon successful validation.<br>
 *         <code>Null</code> upon validation failure
 */
public User validateSession(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
    User thisUser = (User) request.getSession(false).getAttribute(Constants.SESSION_USER);
    LOG.debug("Has user session: " + (thisUser != null));
    if (thisUser == null || !thisUser.isLoggedIn()) {
        LOG.debug("Checking for cookie...");
        // Check cookie for session info and generate a logged in user
        String guid = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_GUID);
        if (guid == null) {
            LOG.debug("No cookie found.");
            return (thisUser == null ? null : thisUser);
        }
        LOG.debug("Cookie found with guid: " + guid);
        // Retrieve prefs to see if user with guid exists
        ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
        // Connection info
        ConnectionElement ce = new ConnectionElement();
        ce.setDriver(prefs.get("SITE.DRIVER"));
        ce.setUrl(prefs.get("SITE.URL"));
        ce.setUsername(prefs.get("SITE.USER"));
        ce.setPassword(prefs.get("SITE.PASSWORD"));
        ConnectionPool sqlDriver = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
        Connection db = null;
        try {
            db = sqlDriver.getConnection(ce);
            // Load the user record from the guid
            thisUser = UserUtils.loadUserFromGuid(db, guid);
            if (thisUser != null) {
                // Track the login
                thisUser.updateLogin(db, request, prefs, null);
                thisUser.setBrowserType(request.getHeader("USER-AGENT"));
                // Apply defaults
                UserUtils.createLoggedInUser(thisUser, db, prefs, context);
                // Extend the cookie
                Cookie userCookie = new Cookie(Constants.COOKIE_USER_GUID, UserUtils.generateGuid(thisUser));
                userCookie.setPath("/");
                // 14 day cookie
                userCookie.setMaxAge(14 * 24 * 60 * 60);
                response.addCookie(userCookie);
            }
        } catch (Exception e) {
            thisUser = null;
            e.printStackTrace();
        } finally {
            if (db != null) {
                sqlDriver.free(db);
            }
        }
        // Add to session
        request.getSession().setAttribute(Constants.SESSION_USER, thisUser);
        request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ce);
    }
    return thisUser;
}

From source file:com.adito.security.DefaultLogonController.java

public void logoffSession(HttpServletRequest request, HttpServletResponse response)
        throws SecurityErrorException {
    if (log.isInfoEnabled())
        log.info("Logging off session " + request.getSession().getId());
    if (request.getSession().getAttribute(Constants.LOGON_TICKET) == null) {
        throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR,
                "The current session does not contain a logon ticket");
    } else {/* ww w. ja  v a 2 s .c  o  m*/
        String ticket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET);
        SessionInfo session = getSessionInfo(ticket);
        logoff(ticket);

        if (request.getCookies() != null) {
            for (int i = 0; i < request.getCookies().length; i++) {
                Cookie cookie = request.getCookies()[i];
                if (cookie.getName().equals(Constants.LOGON_TICKET)
                        || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) {
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
        request.getSession().removeAttribute(Constants.LOGON_TICKET);
        session.invalidate();
    }
}