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.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//from   w  ww.j  a v a 2 s  .c  o  m
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String clientUserName = null;
    String clientIpAddress;/*w  ww  .  j  a v a 2 s. com*/
    boolean requireNewCookie = false;

    try {
        // If the cookie based authentication is already enabled, parse the
        // request and validate the request cookies.
        if (isCookieAuthEnabled) {
            clientUserName = validateCookie(request);
            requireNewCookie = (clientUserName == null);
            if (requireNewCookie) {
                LOG.info("Could not validate cookie sent, will try to generate a new cookie");
            }
        }
        // If the cookie based authentication is not enabled or the request does
        // not have a valid cookie, use the kerberos or password based authentication
        // depending on the server setup.
        if (clientUserName == null) {
            // For a kerberos setup
            if (isKerberosAuthMode(authType)) {
                clientUserName = doKerberosAuth(request);
            }
            // For password based authentication
            else {
                clientUserName = doPasswdAuth(request, authType);
            }
        }
        LOG.debug("Client username: " + clientUserName);

        // Set the thread local username to be used for doAs if true
        SessionManager.setUserName(clientUserName);

        // find proxy user if any from query param
        String doAsQueryParam = getDoAsQueryParam(request.getQueryString());
        if (doAsQueryParam != null) {
            SessionManager.setProxyUserName(doAsQueryParam);
        }

        clientIpAddress = request.getRemoteAddr();
        LOG.debug("Client IP Address: " + clientIpAddress);
        // Set the thread local ip address
        SessionManager.setIpAddress(clientIpAddress);
        // Generate new cookie and add it to the response
        if (requireNewCookie && !authType.equalsIgnoreCase(HiveAuthFactory.AuthTypes.NOSASL.toString())) {
            String cookieToken = HttpAuthUtils.createCookieToken(clientUserName);
            Cookie hs2Cookie = createCookie(signer.signCookie(cookieToken));

            if (isHttpOnlyCookie) {
                response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(hs2Cookie));
            } else {
                response.addCookie(hs2Cookie);
            }
            LOG.info("Cookie added for clientUserName " + clientUserName);
        }
        super.doPost(request, response);
    } catch (HttpAuthenticationException e) {
        LOG.error("Error: ", e);
        // Send a 401 to the client
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (isKerberosAuthMode(authType)) {
            response.addHeader(HttpAuthUtils.WWW_AUTHENTICATE, HttpAuthUtils.NEGOTIATE);
        }
        response.getWriter().println("Authentication Error: " + e.getMessage());
    } finally {
        // Clear the thread locals
        SessionManager.clearUserName();
        SessionManager.clearIpAddress();
        SessionManager.clearProxyUserName();
    }
}

From source file:com.alfaariss.oa.sso.web.profile.web.WebProfile.java

private void handleAuthentication(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
        RequestorPool oRequestorPool, IAuthenticationProfile oSelectedAuthNProfile)
        throws OAException, IOException, UserException {
    _authenticationManager.authenticate(oSelectedAuthNProfile, oRequest, oResponse, oSession);

    switch (oSession.getState()) {
    case AUTHN_OK: {
        oSession.setState(SessionState.POST_AUTHZ_IN_PROGRESS);

        if (oSession.getUser() == null) {
            //Invalid state
            _systemLogger.error(new SystemLogItem(oSession.getId(), SystemErrors.ERROR_INTERNAL,
                    "No user added during authentication, invalid configuration"));
            throw new SSOException(SystemErrors.ERROR_INTERNAL);
        }// w  ww .  j  a  v  a  2  s.  c om

        ITGT oTGT = _ssoService.handleSingleSignon(oSession);
        if (oTGT != null) {
            /* CloudIAM: Add TGT-profile to TGT-attributes */
            String sProfileID = RequestorHelper.entityHostFromRequestor(oSession.getProfileURL());

            //set TGT cookie                 
            Cookie cTGT;
            if (_bTGTProfileEnabled) {
                /* Create cookie in .../profiles/[profile] context */
                cTGT = _cookieTool.createCookie(WebSSOServlet.TGT_COOKIE_NAME, oTGT.getId(),
                        "profiles/" + sProfileID, oRequest);

                /* add profile context as TGT-attribute */
                oTGT.getAttributes().put(WebProfile.class, TGT_ATTR_TGTPROFILE, sProfileID);
                oTGT.persist();
            } else {
                cTGT = _cookieTool.createCookie(WebSSOServlet.TGT_COOKIE_NAME, oTGT.getId(), oRequest);
            }

            /* End of CloudIAM TGT-profile */

            oResponse.addCookie(cTGT);
            addHeaders(oResponse);
        }

        try {
            //Persist Session             
            oSession.persist();
        } catch (OAException e) {
            _systemLogger.warn("Could not persist session", e);
            //Wrap exception
            throw new SSOException(e.getCode(), e);
        }
        //Authentication log -> user authenticated + sProfileId  
        _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.USER_AUTHENTICATED,
                this, oSelectedAuthNProfile.getID()));

        _ssoService.gatherAttributes(oSession);

        //handle post authz
        handlePostAuthorization(oRequest, oResponse, oSession, oRequestorPool);
        break;
    }
    case AUTHN_NOT_SUPPORTED: {
        //Fallback to AuthN selection       
        //set the authN profile list with the not supported profile filtered out
        List<IAuthenticationProfile> listProfiles = oSession.getAuthNProfiles();
        listProfiles.remove(oSelectedAuthNProfile);
        oSession.setAuthNProfiles(listProfiles);

        handleAuthenticationSelection(oRequest, oResponse, oSession, oRequestorPool);
        break;
    }
    case AUTHN_FAILED:
    case USER_CANCELLED:
    case USER_BLOCKED:
    case USER_UNKNOWN: {
        //Authentication finished
        try {
            //Persist Session 
            oSession.persist();
        } catch (OAException e) {
            _systemLogger.warn("Could not persist session", e);
            //Wrap exception
            throw new SSOException(e.getCode(), e);
        }
        //Authentication log performed by manager  
        //Redirect to profile
        oResponse.sendRedirect(oSession.getProfileURL());
        break;
    }
    case AUTHN_IN_PROGRESS: {
        //AuthN Manager handles request                
        break;
    }
    default: {
        //Invalid state
        _systemLogger.fatal(new SystemLogItem(oSession.getId(), SystemErrors.ERROR_INTERNAL,
                "Session state not supported during authentication"));
        throw new SSOException(SystemErrors.ERROR_INTERNAL);
    }
    }
}

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

@RequestMapping(value = "/createAccount", method = RequestMethod.POST)
public String createAccount(Model model, HttpServletRequest request, HttpServletResponse response) {

    String email = request.getParameter(REG_USER_NAME);
    String pwd1 = request.getParameter(REG_PWD);
    String pwd2 = request.getParameter(REG_PWD_RE);

    if (null != email) {
        email = email.trim();// w  w  w  .j a  va  2 s  . co  m
    }

    String acceptLicense = request.getParameter(ACCEPT_LICENSE);

    User user = new User();
    user.setName(email);
    user.setEmail(email);
    user.setPassword(pwd1);
    user.setCreateDate(new Date());
    user.setUpdateDate(new Date());

    if (!TRUE.equals(acceptLicense)) {
        getUserView().getErr().put(ACCEPT_LICENSE_ERR, "Please accept license");
    }

    String landingpage = null;
    try {
        landingpage = URLDecoder.decode(request.getParameter(LOGIN_LANDING_PAGE_PARAM), "utf-8");
    } catch (Exception e) {
        logger.debug(e.getMessage());
    }

    if (null == email || !(email.contains("@"))) {
        getUserView().getErr().put(REG_USER_NAME_ERR, "Invalid user account");
    } else {
        User u = ServiceFactory.getService(UserService.class).queryUserByEmail(email);
        if (u != null) {
            getUserView().getErr().put(REG_USER_NAME_ERR, "account already exist");
        }
    }

    if (pwd1 == null || pwd1.length() < 5) {
        getUserView().getErr().put(REG_PWD_ERR, "Invalid password");
    } else {
        if (pwd2 == null || !pwd1.equals(pwd2)) {
            getUserView().getErr().put(REG_PWD_RE_ERR, "Two passwords are not same");
        }
    }

    if (getUserView().getErr().isEmpty()) {
        final User u = ServiceFactory.getService(UserService.class).saveUser(user);
        if (null != u) {
            getUserView().getMsg().put(REG_USER_NAME_SUC, "Create Account successfully");
            final Map<String, Object> root = new HashMap<String, Object>();
            root.put("user", u);
            u.setPassword(u.getPassword());

            model.addAttribute(USER_INFO, u);
            request.getSession().setAttribute(USER_INFO, u);
            getUserView().setLoginUser(u);
            Cookie cookie = new Cookie(COOKIE_ACCOUNT,
                    Utils.OBJ.getEncryString(u.getEmail() + USER_NAME_PWD_SPLIT + u.getPassword()));
            cookie.setMaxAge(99999999);
            cookie.setPath("/");
            response.addCookie(cookie);

            new Thread() {
                public void run() {
                    try {
                        EmailTools.sendMail("register", "Welcome to Honeybuy.com, New Member Registration",
                                root, u.getName());
                    } catch (Exception e) {

                    }
                };
            }.start();

        }
    }

    if (StringUtils.isNotBlank(landingpage)) {
        getUserView().setRequestPage(landingpage);
    }
    model.addAttribute(REG_USER, user);

    return "login";
}

From source file:com.ssbusy.controller.catalog.CategoryController.java

@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView model = new ModelAndView();
    MyCustomer customer = (MyCustomer) CustomerState.getCustomer();

    HttpSession session = request.getSession();
    MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode");
    Boolean w_flag = Boolean.FALSE;
    // cookies//ww w  .j  av  a 2s  .c o  m
    String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    int count = 0;// ??
    Cookie cookies[] = request.getCookies();
    Boolean uiv2 = null;
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (dateTime.equals(c.getName())) {
                count = Integer.valueOf(c.getValue());
                break;
                // } else if ("uiv2".equals(c.getName())) {
                // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie
            }
        }
    }
    if (cookies != null) {
        for (Cookie c : cookies) {
            if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) {
                model.addObject("rember", c.getValue());
                break;
            }
        }
    }
    // String uiParam = request.getParameter("uiv2");
    // if (StringUtils.isNotEmpty(uiParam)) { // 1 param
    // uiv2 = Boolean.valueOf(uiParam);
    // Cookie c = new Cookie("uiv2", uiv2.toString());
    // c.setPath("/");
    // c.setMaxAge(60 * 60 * 24 * 360);
    // response.addCookie(c);
    // } else if (uiv2 == null) {
    uiv2 = Boolean.TRUE; // 3 default. 
    // }
    session.setAttribute("uiv2", uiv2);
    // LOG.warn("uiv2=" + uiv2);

    if (myOfferCode != null) {
        if (customer.isRegistered())
            giftService.updateOwnerCustomer(customer, myOfferCode);
        else
            myOfferCode = null;
    } else if (count < maxoffercodeCount) {
        myOfferCode = giftService.getgift(customer);
        if (myOfferCode != null) {
            if (customer.isAnonymous()) {
                session.setAttribute("bonusOfferCode", myOfferCode);
                model.addObject("bonusOfferCode", myOfferCode);
                myOfferCode = null;
            }
        }
    }
    if (myOfferCode != null) {
        session.removeAttribute("bonusOfferCode");
        model.addObject("bonusOfferCode", myOfferCode);
        Cookie c = new Cookie(dateTime, String.valueOf(count + 1));
        c.setPath("/");
        c.setMaxAge(60 * 60 * 24);
        response.addCookie(c);
        LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr());
    }

    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the
        // field to the
        // product search criteria expected format. This is used in
        // multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical
        // URLs

        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }

        parameters.remove(ProductSearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");

        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        model.setViewName("redirect:" + newUrl);
    } else {
        // Else, if we received a GET to the category URL (either the user
        // clicked this link or we redirected
        // from the POST method, we can actually process the results

        Category category = (Category) request
                .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME);
        assert (category != null);

        List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category);
        ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets);

        String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING);
        ProductSearchResult result;

        List<FulfillmentLocation> locations = null;
        try {
            // 
            if (customer != null && customer.getRegion() != null) {
                InventorySolrSearchServiceExtensionHandler.customerLocation
                        .set(locations = customer.getRegion().getFulfillmentLocations());
            }
            if (StringUtils.isNotBlank(searchTerm)) {
                result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria);
            } else {
                result = searchService.findProductsByCategory(category, searchCriteria);
            }
        } finally {
            InventorySolrSearchServiceExtensionHandler.customerLocation.remove();
        }

        facetService.setActiveFacetResults(result.getFacets(), request);
        List<Product> products = result.getProducts();

        if (products != null && products.size() > 0) {
            List<String> prodIds = new ArrayList<String>(products.size());
            for (Product product : products) {
                prodIds.add(String.valueOf(product.getId()));
            }
            model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT));

            // ?productinventories
            if (locations != null) {
                Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations);
                model.addObject("inventories", invs);
            }
        }

        model.addObject(PRODUCTS_ATTRIBUTE_NAME, products);
        model.addObject(CATEGORY_ATTRIBUTE_NAME, category);
        // facets
        List<SearchFacetDTO> facets = result.getFacets();
        if (facets != null) {
            _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) {
                SearchFacetDTO dto = itr.next();
                if (dto != null && dto.getFacetValues() != null) {
                    for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) {
                        if (searchFacetDTO != null)
                            if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0)
                                continue _nextFact;
                    }
                }
                itr.remove();
            }
            model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets());
        }
        model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);

        // TODO temp
        String view = category.getDisplayTemplate();
        if (StringUtils.isEmpty(view))
            view = getDefaultCategoryView();
        if (request.getRequestURI().startsWith("/weixin/")) {
            view = "weixin/catalog/w_category_item";
            w_flag = Boolean.TRUE;
        }
        if (uiv2) {
            if ("layout/home".equals(view))
                view = "v2/home";
            else {
                if (!view.startsWith("activity") && !view.startsWith("weixin/")) {
                    view = "v2/" + view;
                }

            }
        }
        session.setAttribute("w_flag", w_flag);
        model.setViewName(view);
    }
    // if (isAjaxRequest(request)) {
    // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM);
    // model.addObject("ajax", Boolean.TRUE);
    // }
    return model;
}

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

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*from  w  w w .ja v a2s  .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.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    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);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}

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

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);// w w w .  j  av  a  2 s. co  m
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("adito.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}

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

private SessionInfo addLogonTicket(HttpServletRequest request, HttpServletResponse response, User user,
        InetAddress address, int sessionType) {
    String logonTicket = TicketGenerator.getInstance().generateUniqueTicket("SLX");
    if (log.isInfoEnabled())
        log.info("Adding logon ticket to session " + request.getSession().getId());
    request.getSession().setAttribute(Constants.LOGON_TICKET, logonTicket);
    request.setAttribute(Constants.LOGON_TICKET, logonTicket);
    String userAgent = request.getHeader("User-Agent");
    SessionInfo info = SessionInfo.nextSession(request.getSession(), logonTicket, user, address, sessionType,
            userAgent);/*from   ww  w  .j av a2s. c  om*/
    request.getSession().setAttribute(Constants.SESSION_INFO, info);
    try {
        String sessionIdentifier = SystemProperties.get("sslexplorer.cookie", "JSESSIONID");
        String sessionId = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equalsIgnoreCase(sessionIdentifier)) {
                sessionId = cookies[i].getValue();
                break;
            }
        }
        if (sessionId != null) {
            logonsBySessionId.put(sessionId, info);
        } else
            log.warn("Could not find session id using identifier " + sessionIdentifier + " in HTTP request");
    } catch (Exception ex) {
        log.warn("Failed to determine HTTP session id", ex);
    }
    logons.put(logonTicket, info);
    /**
     * Set the normal logon ticket without a domain - this works in almost
     * all circumstances
     */
    Cookie cookie = new Cookie(Constants.LOGON_TICKET, logonTicket);
    cookie.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    /**
     * Set a logon ticket for the domain - this is require to make active
     * dns work.
     */
    Cookie cookie2 = new Cookie(Constants.DOMAIN_LOGON_TICKET, logonTicket);
    cookie2.setMaxAge(Property.getPropertyInt(new SystemConfigKey("security.session.maxCookieAge")));
    cookie2.setPath("/");
    // We now set the domain on the cookie so the new Active DNS feature for
    // Reverse Proxy works correctly
    String host = request.getHeader("Host");
    if (host != null) {
        HostService hostService = new HostService(host);
        cookie2.setDomain(hostService.getHost());
    }
    cookie.setSecure(true);
    response.addCookie(cookie2);
    return info;
}