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

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

Introduction

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

Prototype

Serializable getId();

Source Link

Document

Returns the unique identifier assigned by the system upon session creation.

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.  ja  v  a  2s . 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:cn.com.xl.system.controller.LoginController.java

License:Apache License

/**
 * //from ww w .  j  av a2 s  .com
 */
@Json
@Before(LoginValidator.class)
@PostMapping("/login")
public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
    String account = getParameter("account");
    String password = getParameter("password");
    String imgCode = getParameter("imgCode");
    if (!validateCaptcha(response, imgCode)) {
        return error("??");
    }
    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        Session session = ShiroKit.getSession();
        LogKit.println("\nsessionID   : {} ", session.getId());
        LogKit.println("sessionHost   : {}", session.getHost());
        LogKit.println("sessionTimeOut   : {}", session.getTimeout());
    } catch (UnknownAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (DisabledAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (IncorrectCredentialsException e) {
        LOGGER.error("?!", e);
        return error("?");
    } catch (RuntimeException e) {
        LOGGER.error(",??!", e);
        return error(",??");
    }
    doLog(ShiroKit.getSession(), "");
    return success("?");
}

From source file:cn.com.xl.system.controller.LoginController.java

License:Apache License

public void doLog(Session session, String type) {
    if (!BladeLogManager.isDoLog()) {
        return;/*  www  .  j a  va2s .c om*/
    }
    try {
        LoginLog log = new LoginLog();
        String msg = Func.format("[sessionID]: {} [sessionHost]: {} [sessionHost]: {}", session.getId(),
                session.getHost(), session.getTimeout());
        log.setLogname(type);
        log.setMethod(msg);
        log.setCreatetime(new Date());
        log.setSucceed("1");
        log.setUserid(Func.toStr(ShiroKit.getUser().getId()));
        Blade.create(LoginLog.class).save(log);
    } catch (Exception ex) {
        LogKit.logNothing(ex);
    }
}

From source file:cn.powerdash.libsystem.common.security.SecurityContext.java

License:Open Source License

/**
 * Description: ???, ???//from  ww  w .  ja  va2s . c o m
 * 
 * @param userId
 * @param password
 * @return the new session
 * @throws IncorrectCredentialsException
 *             ?
 * @throws LockedAccountException
 *             ?
 */
public static Session login(String userName, String password)
        throws IncorrectCredentialsException, LockedAccountException {
    long start = System.currentTimeMillis();
    UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
    Subject currentUser = SecurityUtils.getSubject();
    // This is to prevent session fixation attack, see: https://issues.apache.org/jira/browse/SHIRO-170
    currentUser.getSession().stop();
    // this will create a new session by default in applications that allow session state:
    currentUser.login(token);
    Session session = currentUser.getSession();
    LOGGER.debug("User {} login successfully, session id {}", userName, session.getId());
    UserService userService = ApplicationContextUtil.getBean(UserService.class);
    User user = userService.findUserByUserName(userName);
    session.setAttribute(USER_KEY, user);
    long end = System.currentTimeMillis();
    LOGGER.debug("login() completed for user {}, total time spent: {}ms", userName, end - start);
    return session;
}

From source file:com.aerospike.shiro.AerospikeSessionDAO.java

License:Apache License

@Override
public void doDelete(Session session) {
    log.info("Deleting session " + session.getId());
    Key key = new Key(this.namespace, this.setname, (String) session.getId());
    this.client.delete(null, key);
}

From source file:com.aerospike.shiro.AerospikeSessionDAO.java

License:Apache License

@Override
public void doUpdate(Session session) throws UnknownSessionException {
    Key key = new Key(this.namespace, this.setname, (String) session.getId());
    Record rec = this.client.get(null, key);
    if (rec != null) {
        this.storeSession((String) session.getId(), session);
    } else {//from  www .j a va 2s.c  o  m
        throw new UnknownSessionException();
    }
}

From source file:com.baguaz.module.user.BgzSessionListener.java

License:Apache License

private String buildLogStr(Session session) {
    StringBuilder sb = new StringBuilder();
    sb.append("\n#################################################").append("\nid          :")
            .append(session.getId())
            .append("\nstart       :"
                    + DateFormatUtils.format(session.getStartTimestamp(), "yyyy-MM-dd HH:mm:ss"))
            .append("\nlast        :"
                    + DateFormatUtils.format(session.getLastAccessTime(), "yyyy-MM-dd HH:mm:ss"))
            .append("\ntimeout(min):" + session.getTimeout() / (1000 * 60))
            .append("\nhost        :" + session.getHost())
            .append("\nattr keys   :" + session.getAttributeKeys())
            .append("\n#################################################");
    return sb.toString();
}

From source file:com.biu.system.controller.LoginController.java

License:Apache License

/**
 * // ww w  .java  2s .  c  o m
 */
@Before(LoginValidator.class)
@ResponseBody
@PostMapping("/login")
public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
    String account = getParameter("account");
    String password = getParameter("password");
    String imgCode = getParameter("imgCode");
    if (!validateCaptcha(response, imgCode)) {
        return error("??");
    }
    Subject currentUser = ShiroKit.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(account, password.toCharArray());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        Session session = ShiroKit.getSession();
        LogKit.println("\nsessionID   : {} ", session.getId());
        LogKit.println("sessionHost   : {}", session.getHost());
        LogKit.println("sessionTimeOut   : {}", session.getTimeout());
    } catch (UnknownAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (DisabledAccountException e) {
        LOGGER.error("??!", e);
        return error("??");
    } catch (IncorrectCredentialsException e) {
        LOGGER.error("?!", e);
        return error("?");
    } catch (RuntimeException e) {
        LOGGER.error(",??!", e);
        return error(",??");
    }
    return success("?");
}

From source file:com.comp.pruebaconshiro.ShiroAuthService.java

public void testAuth() {

    // simulate a username/password (plaintext) token created in response to
    // a login attempt:
    UsernamePasswordToken token = new UsernamePasswordToken("usuario", "cristian");
    token.setRememberMe(true);/*from  ww w  .  j  a va2s.c om*/

    boolean loggedIn;
    Session session = null;
    Subject currentUser = SecurityUtils.getSubject();

    try {
        currentUser.login(token);
        session = currentUser.getSession();
        System.out.println("Session Id: " + session.getId());
        loggedIn = true;
    } catch (Exception ex) {
        loggedIn = false;
    }

    Serializable sessionId = session.getId();
    if (loggedIn) {

        Subject requestSubject = new Subject.Builder().sessionId(sessionId).buildSubject();
        System.out.println("Es admin = " + requestSubject.hasRole("admin"));//Should return true
        System.out.println("Is Authenticated = " + requestSubject.isAuthenticated());//Should return true
        System.out.println("Is Remembered = " + requestSubject.isRemembered());
    } else {
        System.out.println("Not logged in.");
    }
    System.exit(0);
}

From source file:com.flowlogix.ejb.StatefulUtil.java

License:Apache License

/**
 * Pings all pingable SFSBs in the session
 * //w  w w.  ja  va  2  s .co m
 * @param session 
 * @return true if successful, false if any of the pings failed
 */
public static boolean pingStateful(Session session) {
    boolean rv = true;

    List<String> attrNames = FluentIterable.from(session.getAttributeKeys())
            .transform(new Function<Object, String>() {
                @Override
                public String apply(Object f) {
                    if (f instanceof String) {
                        return (String) f;
                    } else {
                        return null;
                    }
                }
            }).filter(Predicates.and(Predicates.notNull(), Predicates.contains(ejbPattern))).toList();
    for (String attrName : attrNames) {
        synchronized (session.getId().toString().intern()) {
            try {
                Object _pingable = session.getAttribute(attrName);
                if (_pingable instanceof Pingable) {
                    Pingable pingable = (Pingable) _pingable;
                    pingable.ping();
                }
            } catch (EJBException e) {
                log.debug("Failed to Ping Stateful EJB: ", e);
                rv = false; // signal failure if any of the pings fail
                session.removeAttribute(attrName);
            }
        }
    }

    return rv;
}