Example usage for javax.servlet.http Cookie setMaxAge

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

Introduction

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

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Sets the maximum age for cookies. The maximum age is configured in xwiki.cfg using the
 * xwiki.authentication.cookielife parameter (number of days). The default age is 14 days.
 * /*from   w  w  w  .  j a  v a2s. c  o  m*/
 * @param cookie The cookie for which the expiration date is configured.
 */
private void setMaxAge(Cookie cookie) {
    try {
        cookie.setMaxAge(Math.round(60 * 60 * 24 * Float.parseFloat(this.cookieLife)));
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Failed setting cookie Max age with duration " + this.cookieLife);
        }
    }
}

From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java

Cookie createAuthCookie(HttpServletRequest httpReq, String authToken, long expiresMillis) {
    Cookie authCookie = new Cookie(getAuthCookieName(httpReq), authToken);
    authCookie.setPath("/");
    // if positive it is a persistent session, else a transient one and we don't have to set the cookie age
    if (expiresMillis > 0) {
        int secondsToLive = (int) ((expiresMillis - System.currentTimeMillis()) / 1000);
        authCookie.setMaxAge(secondsToLive);
    } else if (expiresMillis == 0) {
        // to delete the cookie
        authCookie.setMaxAge(0);/*w  w  w.  j  a  va  2  s . com*/
    }

    if (isDataCollector) {
        // When an SDC is accessing SCH, set the cookie based on the SDC's scheme
        authCookie.setSecure(httpReq.isSecure());
    } else {
        // When a browser accesses SCH, set the cookie based on the SCH endpoint
        authCookie.setSecure(dpmBaseUrl.startsWith("https"));
    }

    return authCookie;
}

From source file:org.toobsframework.pres.doit.DoItRunner.java

private void runAction(IRequest request, String doItName, Action thisAction, Map<String, Object> params,
        Map<String, Object> responseParams, boolean lastAction) throws Exception {

    String actionType = thisAction.getActionType();
    Object retObj = null;//  ww  w .j av  a2 s. c  om
    if (actionType.equalsIgnoreCase("objectAction")) {
        //Fix the input params using the param mapping for 
        //this configuration.
        if (thisAction.getParameters() != null) {
            // Cant do this for now cause of the array problem
            //ParameterUtil.mapParameters(thisAction.getParameters().getParameter(), params, params, doItName);
            ParameterUtil.mapDoItParameters(request, thisAction.getParameters().getParameter(), params, params,
                    true);
        }
        try {
            if (thisAction.isExtended()) {
                retObj = this.getDataProvider().dispatchActionEx(request, thisAction.getAction(),
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getServiceProvider(),
                                params))[0],
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getInputObjectType(),
                                params))[0],
                        thisAction.getReturnObjectType(),
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getGuidParam(), params))[0],
                        thisAction.getPermissionContext(), thisAction.getIndexParam(),
                        thisAction.getNamespace(), params, responseParams);
            } else {
                retObj = this.getDataProvider().dispatchAction(thisAction.getAction(),
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getServiceProvider(),
                                params))[0],
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getInputObjectType(),
                                params))[0],
                        thisAction.getReturnObjectType(),
                        ((String[]) ParameterUtil.resolveParam(request, thisAction.getGuidParam(), params))[0],
                        thisAction.getPermissionContext(), thisAction.getIndexParam(),
                        thisAction.getNamespace(), params, responseParams);
            }
            /* TODO: Remove this later 
            Iterator iter = responseParams.keySet().iterator();
            while (iter.hasNext()) {
              Object key = iter.next();
              params.put((String)key, responseParams.get(key));
            }
            */
        } catch (Exception e) {
            /* TODO Check to see if making responseParams work as error forward params
             * cause this sucks balls
            if (e.getCause() instanceof ValidationException) {
              responseParams.put("ErrorForwardParams", params.get("ErrorForwardParams"));
            }
            */
            throw e;
        }
    } else if (actionType.equalsIgnoreCase("cookieAction")) {
        String cookieName = ((String[]) ParameterUtil.resolveParam(request, params.get("cookieName"),
                params))[0];
        String cookieValue = ((String[]) ParameterUtil.resolveParam(request, params.get("cookieValue"),
                params))[0];
        int maxAge = -1;
        try {
            maxAge = Integer.parseInt(
                    ((String[]) ParameterUtil.resolveParam(request, params.get("maxAge"), params))[0]);
        } catch (Exception e) {
        }

        Cookie doitCookie = new Cookie(cookieName, cookieValue);
        doitCookie.setMaxAge(maxAge);
        componentRequestManager.get().getHttpResponse().addCookie(doitCookie);
    } else if (actionType.equalsIgnoreCase("sessionAction")) {
        Map<String, Object> sessionMap = new HashMap<String, Object>();

        if (thisAction.getParameters() != null) {
            ParameterUtil.mapDoItParameters(request, thisAction.getParameters().getParameter(), params,
                    sessionMap, true);
        }
        HttpSession session = componentRequestManager.get().getHttpRequest().getSession();
        Iterator<Map.Entry<String, Object>> iter = sessionMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = iter.next();
            session.setAttribute(entry.getKey(), entry.getValue());
        }
    } else if (actionType.equalsIgnoreCase("indexAction") && lastAction) {
        if (this.getIndexBuilder() != null) {
            indexBuilder.buildIndexes(thisAction.getServiceProvider());
        }
    } else {
        //TODO -- Add the ability to run scripts defined in config here.
    }

    //HashMap responseParams = new HashMap();
    //Add the output params into the request for 
    //this configuration.
    if (thisAction.getOutputParameters() != null && retObj != null) {
        JXPathContext context = null;
        if ("delete".equalsIgnoreCase(thisAction.getAction())) {
            context = JXPathContext.newContext(responseParams);
            responseParams.put("deleted", String.valueOf(((Boolean) retObj).booleanValue()));
        } else {
            context = JXPathContext.newContext(retObj);
        }
        Parameter[] paramMap = thisAction.getOutputParameters().getParameter();
        for (int j = 0; j < paramMap.length; j++) {
            Parameter thisParam = paramMap[j];
            String[] paramPath = ParameterUtil.resolveParam(request, thisParam.getPath(), params);
            String[] paramName = ParameterUtil.resolveParam(request, thisParam.getName(), params);
            Object value = null;
            for (int i = 0; i < paramName.length; i++) {
                if (thisParam.getIsStatic()) {
                    value = thisParam.getPath();
                } else {
                    try {
                        value = context.getValue(paramPath[i]);
                    } catch (org.apache.commons.jxpath.JXPathException e) {
                        if (!thisParam.getIgnoreNull()) {
                            log.warn("Problem evaluating jxpath: " + paramName[i] + " value: " + paramPath[i]
                                    + " action: " + thisAction.getServiceProvider(), e);
                        }
                        continue;
                    }
                    if (value != null && value.getClass().isArray()) {
                        value = ((String[]) value)[0];
                    }
                }
                responseParams.put(paramName[i], value);
            }
        }
    }

    //Add 
    if (thisAction.getReturnAttributeName() != null && retObj != null) {
        JXPathContext context = JXPathContext.newContext(retObj);
        responseParams.put(thisAction.getReturnAttributeName(), context.getValue("./valueObject/guid"));
    }

    Iterator<String> iter = responseParams.keySet().iterator();
    while (iter.hasNext()) {
        String key = iter.next();
        params.put(key, responseParams.get(key));
    }

}

From source file:com.nominanuda.web.http.ServletHelper.java

public Cookie servletCookie(HttpCookie c) {
    Cookie _c = new Cookie(c.getName(), c.getValue());
    if (c.getComment() != null) {
        _c.setComment(c.getComment());/*from w ww.  j  a v a 2 s.  c  o m*/
    }
    if (c.getDomain() != null) {
        _c.setDomain(c.getDomain());
    }
    if (c.getPath() != null) {
        _c.setPath(c.getPath());
    }
    _c.setSecure(c.getSecure());
    _c.setVersion(c.getVersion());
    _c.setHttpOnly(c.getDiscard());
    _c.setMaxAge((int) c.getMaxAge());
    return _c;
}

From source file:ai.susi.server.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {/*from  w w w. j a  v  a2  s .  c  o m*/
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:com.techngage.smartbin.Controller.java

private void initializeRoutes() throws IOException {

    // Get all the available truck ids
    get(new Route("/truck") {
        @Override/*from  ww w . j a v  a2 s.co  m*/
        public Object handle(Request request, Response response) {
            List<Document> truckList = truckDAO.getTruckIds();
            String truckStr = "";
            String truckStrTmp = "";
            for (int i = 0; i < truckList.size(); i++) {
                truckStr = (String) truckList.get(i).get("truckid");
                if (i == truckList.size() - 1) {
                    truckStrTmp = truckStrTmp + truckStr;
                } else {
                    truckStrTmp = truckStrTmp + truckStr + ";";
                }
            }
            return truckStrTmp;
        }
    });

    // present signup form for smartbin app
    get(new Route("/unassign") {
        @Override
        public Object handle(Request request, Response response) {
            // Unassign route to truck.
            int routeId = Integer.parseInt(request.queryParams("routeid"));
            String truckId = request.queryParams("truckid");
            String status = routeDAO.unassignRoute(truckId, routeId);
            truckDAO.updateTruckAsUnAssigned(truckId, routeDAO.checkRouteAssigned(truckId));
            return status;
        }
    });

    // present signup form for smartbin app
    get(new Route("/assign") {
        @Override
        public Object handle(Request request, Response response) {
            // Assign route to truck.
            int routeId = Integer.parseInt(request.queryParams("routeid"));
            String truckId = request.queryParams("truckid");
            String status = routeDAO.assignRoute(truckId, routeId);
            truckDAO.updateTruckAsAssigned(truckId);
            return status;
        }
    });

    // insert location and coordinates, public api called from micro-controller
    post(new Route("/insert") {
        @Override
        public Object handle(Request request, Response response) {
            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("You are not authorized");
                response.status(403);
            } else {
                // Insert route.
                String location = request.queryParams("location");
                String coordinates = request.queryParams("coordinates");
                boolean isDuplicate = locationDAO.checkDuplicateRoute(coordinates);
                if (location != null && coordinates != null && !isDuplicate) {
                    locationDAO.insertRoute(location, coordinates);
                }
            }
            return null;
        }
    });

    // handle the signup to smartbin web app
    post(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            String email = request.queryParams("email");
            String username = request.queryParams("username");
            String password = request.queryParams("password");
            String verify = request.queryParams("verify");

            HashMap<String, String> root = new HashMap<String, String>();
            root.put("username", StringEscapeUtils.escapeHtml4(username));
            root.put("email", StringEscapeUtils.escapeHtml4(email));

            if (validateSignup(username, password, verify, email, root)) {
                // good user
                System.out.println("Signup: Creating user with: " + username + " " + password);
                if (!userDAO.addUser(username, password, email)) {
                    // duplicate user
                    root.put("username_error", "Username already in use, Please choose another");
                    template.process(root, writer);
                } else {
                    // good user, let's start a session
                    String sessionID = sessionDAO.startSession(username);
                    System.out.println("Session ID is" + sessionID);

                    response.raw().addCookie(new Cookie("session", sessionID));
                    response.redirect("/dashboard");
                }
            } else {
                // bad signup
                System.out.println("User Registration did not validate");
                template.process(root, writer);
            }
        }
    });

    // present signup form for smartbin app
    get(new FreemarkerBasedRoute("/signup", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            SimpleHash root = new SimpleHash();

            // initialize values for the form.
            root.put("username", "");
            root.put("password", "");
            root.put("email", "");
            root.put("password_error", "");
            root.put("username_error", "");
            root.put("email_error", "");
            root.put("verify_error", "");

            template.process(root, writer);
        }
    });

    get(new FreemarkerBasedRoute("/dashboard", "dashboard.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String cookie = getSessionCookie(request);
            String username = sessionDAO.findUserNameBySessionId(cookie);

            if (username == null) {
                System.out.println("dashboard() can't identify the user, redirecting to signup");
                response.redirect("/login");

            } else {
                SimpleHash root = new SimpleHash();
                int totRoutes = 3;
                List<Document> routes = routeDAO.getRoutes(totRoutes);
                root.put("username", username);
                root.put("names", routeDAO.getRoute());
                root.put("myroutes", routes);
                root.put("totallimitedroutes", totRoutes);
                root.put("totalescalatedroutes", routeDAO.getEscalatedRoutes().size());
                root.put("totalcompletedroutes", routeDAO.getCompletedRoutes().size());
                root.put("totalinprogressroutes", routeDAO.getEscalatedRoutes().size());

                List<Document> truckList = truckDAO.getTruckIds();
                /*String truckStr = "";
                String truckStrTmp = "";
                for(int i=0;i<truckList.size();i++){
                truckStr = (String)truckList.get(i).get("truckid");
                if(i == truckList.size()-1){
                    truckStrTmp = truckStrTmp + truckStr;
                } else {
                    truckStrTmp = truckStrTmp + truckStr + ";";
                }
                }*/
                root.put("trucklist", truckList);

                template.process(root, writer);
            }
        }
    });

    // present the login page
    get(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("username", "");
            root.put("login_error", "");

            template.process(root, writer);
        }
    });

    // process output coming from login form. On success redirect folks to the dashboard
    // on failure, just return an error and let them try again.
    post(new FreemarkerBasedRoute("/login", "login.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String username = request.queryParams("username");
            String password = request.queryParams("password");

            System.out.println("Login: User submitted: " + username + "  " + password);

            Document user = userDAO.validateLogin(username, password);

            if (user != null) {

                // valid user, let's log them in
                String sessionID = sessionDAO.startSession(user.get("_id").toString());

                if (sessionID == null) {
                    response.redirect("/internal_error");
                } else {
                    // set the cookie for the user's browser
                    response.raw().addCookie(new Cookie("session", sessionID));

                    response.redirect("/dashboard");
                }
            } else {
                SimpleHash root = new SimpleHash();

                root.put("username", StringEscapeUtils.escapeHtml4(username));
                root.put("password", "");
                root.put("login_error", "Invalid Login");
                template.process(root, writer);
            }
        }
    });

    // allows the user to logout of the smartbin app
    get(new FreemarkerBasedRoute("/logout", "signup.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {

            String sessionID = getSessionCookie(request);
            if (sessionID == null) {
                // no session to end
                response.redirect("/login");
            } else {
                // deletes from session table
                sessionDAO.endSession(sessionID);

                // this should delete the cookie
                Cookie c = getSessionCookieActual(request);
                c.setMaxAge(0);

                response.raw().addCookie(c);

                response.redirect("/login");
            }
        }
    });

    // used to process internal errors
    get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash root = new SimpleHash();

            root.put("error", "System has encountered an error.");
            template.process(root, writer);
        }
    });
}

From source file:com.maydesk.base.PDUserSession.java

public void setCookie(String cookieName, String value) {
    Cookie userCookie = new Cookie(cookieName, value);
    ContainerContext ctx = (ContainerContext) ApplicationInstance.getActive()
            .getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
    userCookie.setMaxAge(60 * 60 * 24 * 360); // expires after 360 days
    ctx.addCookie(userCookie);/*from  ww w.j a  v  a2  s.c om*/
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Cookie makeAuthTokenCookie(AuthToken attrlist, CookieUse use) {

    String cookieValue = attrlist.getTokenString();

    if (use == CookieUse.EXTERNAL) {
        // Generate digital signature and add to token string
        byte[] signature = generateSignature(cookieValue);
        cookieValue = cookieValue + "-" + Base64.encodeBase64String(signature);
    }/*  w  w  w.j ava2s .  c  o  m*/

    logger.debug("Cookie value: " + cookieValue);

    Cookie c = new Cookie(ConfigurationListener.getTokenName(), cookieValue);
    Long expiry = attrlist.getExpirationDate() / 1000L;
    c.setMaxAge(expiry.intValue());
    return c;

}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie//w w  w .  j  a  va  2s .  com
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

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

protected boolean auth(String spEntityID, HttpServletRequest request, HttpServletResponse response) {
    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }/*from  w  ww.j  a v a2 s. c om*/
            }
        }
    }

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

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

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

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

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

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

    return false;
}