Example usage for org.apache.shiro.session Session setTimeout

List of usage examples for org.apache.shiro.session Session setTimeout

Introduction

In this page you can find the example usage for org.apache.shiro.session Session setTimeout.

Prototype

void setTimeout(long maxIdleTimeInMillis) throws InvalidSessionException;

Source Link

Document

Sets the time in milliseconds that the session may remain idle before expiring.

Usage

From source file:br.com.criativasoft.opendevice.wsrest.resource.AuthRest.java

License:Open Source License

@POST
@Produces(MediaType.APPLICATION_JSON)//from w w  w.  j  av  a 2  s .  c om
public Response loginForm(@Context AtmosphereResource res, @Auth Subject currentUser,
        @FormParam("username") String username, @FormParam("password") String password) {

    if (currentUser.isAuthenticated())
        return noCache(Response.status(Status.OK).entity("{\"messages\":[\"Already logged\"]}"));

    Response response = doLogin(currentUser, username, password, false);

    if (currentUser.isAuthenticated()) {

        AccountPrincipal principal = (AccountPrincipal) currentUser.getPrincipal();

        // Generate Cookie to indentify user on Shiro (see NewShiroInterceptor)
        Session session = currentUser.getSession(true); // this will force session creation
        javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(AuthRest.SESSION_ID,
                (String) session.getId());
        cookie.setPath("/");
        res.getResponse().addCookie(cookie);
        session.setTimeout((1000 * 60) * 30); // min

        //            // Generate Cookie to indentify ApiKey/AuthToken
        //            cookie = new javax.servlet.http.Cookie(TenantProvider.HTTP_HEADER_KEY, principal.getAccountUUID()); // (String) session.getId()
        //            cookie.setPath("/");
        //            res.getResponse().addCookie(cookie);

    }

    return response;

}

From source file:com.fengduo.spark.commons.shiro.session.SessionManager.java

License:Open Source License

@Override
protected Session newSessionInstance(SessionContext context) {
    Session session = super.newSessionInstance(context);
    session.setTimeout(getGlobalSessionTimeout());
    return session;
}

From source file:com.github.richardwilly98.esdms.shiro.EsSessionDAO.java

License:Open Source License

@Override
protected Serializable doCreate(Session session) {
    try {/*  ww  w  .  j  ava  2  s.  c  o m*/
        session.setTimeout(sessionTimeout);
        if (log.isTraceEnabled()) {
            log.trace(String.format("*** doCreate - %s - timeout: %s", session, session.getTimeout()));
        }
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        SessionImpl s = new SessionImpl.Builder().id(sessionId.toString())
                .createTime(session.getStartTimestamp()).lastAccessTime(session.getLastAccessTime())
                .active(true).timeout(session.getTimeout()).build();
        s = authenticationService.create(s);
        EsSession esSession = new EsSession(s);
        return esSession.getId();
    } catch (ServiceException ex) {
        log.error("doCreate failed", ex);
    }
    return null;
}

From source file:com.glaf.shiro.redis.RedisSessionDAO.java

License:Apache License

/**
 * save session//from  w ww.  ja v  a  2 s .  c o m
 * 
 * @param session
 * @throws UnknownSessionException
 */
private void saveSession(Session session) throws UnknownSessionException {
    if (session == null || session.getId() == null) {
        logger.error("session or session id is null");
        return;
    }

    byte[] key = getByteKey(session.getId());
    byte[] value = SerializerUtils.serialize(session);
    session.setTimeout(redisManager.getExpire() * 1000);
    this.redisManager.set(key, value, redisManager.getExpire());
}

From source file:com.imos.sample.Quickstart.java

License:Apache License

public static void main(String[] args) {

    // The easiest way to create a Shiro SecurityManager with configured
    // realms, users, roles and permissions is to use the simple INI config.
    // We'll do that by using a factory that can ingest a .ini file and
    // return a SecurityManager instance:
    // Use the shiro.ini file at the root of the classpath
    // (file: and url: prefixes load from files and urls respectively):
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();

    // for this simple example quickstart, make the SecurityManager
    // accessible as a JVM singleton.  Most applications wouldn't do this
    // and instead rely on their container configuration or web.xml for
    // webapps.  That is outside the scope of this simple quickstart, so
    // we'll just do the bare minimum so you can continue to get a feel
    // for things.
    SecurityUtils.setSecurityManager(securityManager);

    // Now that a simple Shiro environment is set up, let's see what you can do:
    // get the currently executing user:
    Subject currentUser = SecurityUtils.getSubject();
    ///home/alok/Tools/netbean_dev_workspace/AllProjects/SampleShiro/src/main/java/com/imos/sample/Quickstart.java

    // Do some stuff with a Session (no need for a web or EJB container!!!)
    Session session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");

    session.setTimeout(12000);
    System.out.println("Id : " + session.getId());
    System.out.println("Host : " + session.getHost());
    System.out.println("StartTime : " + session.getStartTimestamp());
    System.out.println("Timeout : " + session.getTimeout());

    String value = (String) session.getAttribute("someKey");
    if (value.equals("aValue")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }//  w  w  w  .  j  av a  2s .  c om

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }
    }

    //say who they are:
    //print their identifying principal (in this case, a username):
    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

    //test a role:
    if (currentUser.hasRole("schwartz")) {
        log.info("May the Schwartz be with you!");
    } else {
        log.info("Hello, mere mortal.");
    }

    //test a typed permission (not instance-level)
    if (currentUser.isPermitted("lightsaber:weild")) {
        log.info("You may use a lightsaber ring.  Use it wisely.");
    } else {
        log.info("Sorry, lightsaber rings are for schwartz masters only.");
    }

    //a (very powerful) Instance Level permission:
    if (currentUser.isPermitted("winnebago:drive:eagle5")) {
        log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                + "Here are the keys - have fun!");
    } else {
        log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
    }

    try {
        System.out.println("Delay for 10 sec");
        Thread.sleep(10000);
    } catch (InterruptedException ex) {
        log.error(ex.getMessage());
    }

    try {
        System.out.println("LastAccess : " + session.getLastAccessTime());

        //all done - log out!
        currentUser.logout();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    //        currentUser = SecurityUtils.getSubject();
    System.out.println("\nNew Session");
    session = currentUser.getSession();
    session.setAttribute("someKey", "aValue");

    System.out.println("Id : " + session.getId());
    System.out.println("Host : " + session.getHost());
    System.out.println("StartTime : " + session.getStartTimestamp());
    System.out.println("Timeout : " + session.getTimeout() / 1000);

    // let's login the current user so we can check against roles and permissions:
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
        token.setRememberMe(true);
        try {
            //                currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.info("There is no user with username of " + token.getPrincipal());
        } catch (IncorrectCredentialsException ice) {
            log.info("Password for account " + token.getPrincipal() + " was incorrect!");
        } catch (LockedAccountException lae) {
            log.info("The account for username " + token.getPrincipal() + " is locked.  "
                    + "Please contact your administrator to unlock it.");
        } // ... catch more exceptions here (maybe custom ones specific to your application?
        catch (AuthenticationException ae) {
            //unexpected condition?  error?
        }

        try {
            System.out.println("Delay for 5 sec");
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            log.error(ex.getMessage());
        }

        try {
            System.out.println("Last Access : " + session.getLastAccessTime());

            //all done - log out!
            currentUser.logout();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    System.exit(0);
}

From source file:com.iscas.quickframe.config.MySingleSignOutHandler.java

License:Apache License

/**
 * Destroys the current HTTP session for the given CAS logout request.
 *
 * @param request HTTP request containing a CAS logout message.
 *//*from   w ww.  j a  v  a  2s  .c  o m*/
public Session destroySession(final HttpServletRequest request, RedisCacheSessionDao redisCacheSessionDao) {
    Session sessionx = null;
    final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName);
    if (log.isTraceEnabled()) {
        log.trace("Logout request:\n" + logoutMessage);
    }

    final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex");

    if (CommonUtils.isNotBlank(token)) {
        //           this.sessionMappingStorage.removeRedisSessionByMappingId(token);

        String sessionId = SpringRedisUtil.get(token, String.class);
        if (sessionId != null) {
            SpringRedisUtil.delete(token);
            //sessionx = redisCacheSessionDao.readSession(sessionId);
            sessionx = SpringRedisUtil.get(sessionId, Session.class);
            if (sessionx != null) {
                sessionx.setTimeout(-1);
                sessionx.stop();
            }
            SpringRedisUtil.delete(sessionId);
        }
        final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token);

        if (session != null) {
            String sessionID = session.getId();

            if (log.isDebugEnabled()) {
                log.debug("Invalidating session [" + sessionID + "] for token [" + token + "]");
            }
            try {
                session.invalidate();
            } catch (final IllegalStateException e) {
                log.debug("Error invalidating session.", e);
            }
        }
    }
    return sessionx;
}

From source file:com.local.ask.controller.spring.LoginController.java

@RequiresGuest
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submitLoginForm(@Valid LoginUser loginUser, BindingResult result, Model m,
        HttpServletRequest request) {//from   w w  w  . j  av  a  2 s  .  co  m
    if (!result.hasErrors()) {
        try {
            UserTemp userTemp = new UserTemp(loginUser);
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(userTemp.getEmail(), userTemp.getPassword(),
                    loginUser.getRememberMe()));
            Session session = subject.getSession(true);
            session.setAttribute("user", userTemp);
            session.setTimeout(24 * 3600000);
            m.addAttribute("message", "Successfully logged in person");
            String referer = request.getHeader("referer");
            if (referer != null && !referer.isEmpty()) {
                return REDIRECT + referer;
            }
            referer = (String) SecurityUtils.getSubject().getSession().getAttribute("fallback");
            if (referer != null && !referer.isEmpty()) {
                return REDIRECT + referer;
            }
        } catch (AuthenticationException ex) {
            ex.printStackTrace();
            m.addAttribute("message", "It seems your email is not registered.");
        }
    }
    return "login";
}

From source file:com.parallax.server.blocklyprop.security.BlocklyPropSessionDao.java

/**
 * Inserts a new Session record into the underling EIS (a relational database in this
 * implementation)./*ww w.j  a v a 2 s  . co  m*/
 *
 * @param session
 * the Session object to create in the EIS.
 *
 * @return
 * the EIS id (e.g. primary key) of the created Session object.
 *
 * @implNote
 * After this method is invoked, the Session.getId() method executed on the argument
 * must return a valid session identifier. That is, the following should always be
 * true:
 *
 *    Serializable id = create( session );
 *    id.equals( session.getId() ) == true
 *
 * Implementations are free to throw any exceptions that might occur due to integrity
 * violation constraints or other EIS related errors.
 */
@Override
public Serializable create(Session session) {
    LOG.trace("Create BlocklyProp session");

    // Set session timeout for 8 hours
    session.setTimeout(28800000);

    SimpleSession simpleSession = (SimpleSession) session;

    // Create a unique string and save into the session object
    String uuid = UUID.randomUUID().toString();
    simpleSession.setId(uuid);

    // Get a reference to the static session service and create
    // a session record from the session object and store it in the
    // sessionDao backing store
    SessionServiceImpl.getSessionService().create(convert(simpleSession));
    LOG.info("Creating session: {}", simpleSession.getId());

    // Return a unique session identifier
    return uuid;
}

From source file:com.sanweibook.lingdu.shiro.session.redisSessionDAO.java

License:Apache License

@Override
protected Serializable doCreate(Session session) {
    Serializable sessionId = this.generateSessionId(session);
    this.assignSessionId(session, sessionId);
    session.setTimeout(sessionTomeOut);
    try {/*from  w w w  .j ava 2s  .c  om*/
        redisClientTemplate.setEX(getKeyByte(sessionId), SerializationUtils.serialize(session),
                sessionTomeOut / 1000);
    } catch (UnsupportedEncodingException e) {
        log.error("Set Session's id:{} by byte is error. ", sessionId, e);
    }
    return sessionId;
}

From source file:com.sanweibook.lingdu.shiro.session.redisSessionDAO.java

License:Apache License

@Override
public void update(Session session) throws UnknownSessionException {
    checkSession(session);//from ww  w  .  ja  v  a2  s  . co m
    session.setTimeout(sessionTomeOut);
    try {
        redisClientTemplate.setEX(getKeyByte(session.getId()), SerializationUtils.serialize(session),
                sessionTomeOut / 1000);
    } catch (UnsupportedEncodingException e) {
        log.error("Update Session's id:{} by byte is error. ", session.getId(), e);
    }
}