List of usage examples for org.apache.shiro.session Session getHost
String getHost();
From source file:cn.com.xl.system.controller.LoginController.java
License:Apache License
/** * // w w w. ja v a2s .c o m */ @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;/* w w w . j a va 2 s.c o m*/ } 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: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())// w w w .j av a2s . c o m .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
/** * /*w ww . j av a 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.bright.amp.authc.service.AuthService.java
/** * ?/* w w w . jav a2s. c o m*/ * * @param request * @return */ @Override public boolean login(TsysUser user) throws Exception { Subject currentUser = SecurityUtils.getSubject(); String username = user.getLoginname(); String password = user.getPassword(); // License??? try { UsernamePasswordToken token = new UsernamePasswordToken(username, getEncryptedPassword(password)); token.setRememberMe(false); currentUser.login(token); Session session = currentUser.getSession(); // logger.debug("IP={}", session.getHost()); ShiroUser shUser = (ShiroUser) currentUser.getPrincipal(); // ?? String userIdString = shUser.getId(); TsysUser userData = tsysUserDao.getById(userIdString); if (userData.getVerifyipaddr() != null && userData.getVerifyipaddr() == 1) { String startIpValue = CharTurn.calIPAddress(userData.getStartstandardip()); String endIpValue = CharTurn.calIPAddress(userData.getEndstandardip()); String ipValue = CharTurn.calIPAddress(session.getHost()); if ((startIpValue.compareTo(ipValue) > 0) || (endIpValue.compareTo(ipValue) < 0)) { throw new ParameterException("system.login.invalidip"); } } session.setAttribute("userName", username); // ??? session.setAttribute("userId", userIdString); // ?ID session.setAttribute("userDisplayName", shUser.getName()); // ??? session.setAttribute("ip", session.getHost()); // ?IP /*TUsrUserduration userduration = new TUsrUserduration(); userduration.setUserId(userIdString); userduration.setUserIp(session.getHost()); userdurationDao.insert(userduration);*/ } catch (ParameterException ex) { throw ex; } catch (Exception ex) { ex.printStackTrace(); throw new ParameterException("system.login.invalidpasswd"); } return true; }
From source file:com.ikanow.aleph2.security.db.SessionDb.java
License:Apache License
protected JsonNode serialize(Object session) { ObjectNode sessionOb = null;//from w ww . ja v a 2 s . c om if (session instanceof Session) { Session s = (Session) session; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); sessionOb = mapper.createObjectNode(); sessionOb.put("_id", s.getId().toString()); sessionOb.put("last_access_time", s.getLastAccessTime().getTime()); sessionOb.put("start_time_stamp", s.getStartTimestamp().getTime()); sessionOb.put("timeout", s.getTimeout()); sessionOb.put("host", s.getHost()); ObjectNode attributesOb = sessionOb.putObject("attributes"); for (Iterator<Object> it = s.getAttributeKeys().iterator(); it.hasNext();) { Object key = it.next(); Object value = s.getAttribute(key); if (value != null) { // base64 encode objects in session logger.debug("Storing session attribute:" + key + "=" + value); attributesOb.put(escapeMongoCharacters("" + key), SerializableUtils.serialize(value)); } } } return sessionOb; }
From source file:com.ikanow.aleph2.security.service.IkanowV2SecurityServiceTest.java
License:Apache License
@Test public void testSessionDb() { SessionDb sessionDb = new SessionDb(_service_context); Session session1 = mock(Session.class); when(session1.getId()).thenReturn("123"); when(session1.getHost()).thenReturn("localhost"); Date now = new Date(); when(session1.getLastAccessTime()).thenReturn(now); when(session1.getStartTimestamp()).thenReturn(now); when(session1.getTimeout()).thenReturn(1000L * 60L); when(session1.getAttributeKeys()).thenReturn(Arrays.asList("currentUser")); when(session1.getAttribute(any())).thenReturn("doesnotexist@ikanow.com"); sessionDb.store(session1);//from w w w . j av a 2s. c o m Session session2 = (Session) sessionDb.loadById("123"); assertNotNull(session2); assertEquals(session1.getId(), session2.getId()); assertEquals(session1.getHost(), session2.getHost()); assertEquals(session1.getLastAccessTime(), session2.getLastAccessTime()); assertEquals(session1.getStartTimestamp(), session2.getStartTimestamp()); assertEquals(session1.getAttribute("currentUser"), session2.getAttribute("currentUser")); sessionDb.delete("123"); Session session3 = (Session) sessionDb.loadById("123"); assertNull(session3); }
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);/*from w w w . ja v a 2 s . com*/ 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 + "]"); } // 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.once.crosscloud.controllers.IndexController.java
License:Apache License
/** * /*www .j a v a 2s . c o m*/ * ? * 1??Subject,?shiro?,? * 2???,UsernamePasswordToken,?shiro? * 3??ShiroDbRealmdoGetAuthenticationInfo? * 4?????,? * * @param accountName ?? * @param password ? * @return */ @RequestMapping(value = "login.html", method = RequestMethod.POST, produces = "text/html; charset=utf-8") public String userLogin(String accountName, String password, String captcha, Boolean rememberMe, HttpServletRequest request) { UsernamePasswordToken token = null; try { //session?servlet???text String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); //???? if (!captcha.equalsIgnoreCase(expected)) { request.setAttribute("error", "???"); return "/login"; } else { // ?Subject,?shiro?,? Subject subject = SecurityUtils.getSubject(); token = new UsernamePasswordToken(accountName, password); //token.setRememberMe(rememberMe); subject.login(token); if (subject.isAuthenticated()) { LoginInfoEntity loginInfo = new LoginInfoEntity(); Session session = SecurityUtils.getSubject().getSession(); loginInfo.setUserId(Integer.valueOf(session.getAttribute("userSessionId").toString())); loginInfo.setAccountName(accountName); loginInfo.setLoginIp(session.getHost()); loginInfoService.log(loginInfo); request.removeAttribute("error"); } else { token.clear(); request.setAttribute("error", "?????"); return "/login"; } } } catch (LockedAccountException e) { token.clear(); request.setAttribute("error", "?,??10???"); return "/login"; } catch (ExcessiveAttemptsException e) { token.clear(); request.setAttribute("error", "5,???10!"); return "/login"; } catch (AuthenticationException e) { token.clear(); request.setAttribute("error", "?????"); return "/login"; } catch (Exception e) { token.clear(); request.setAttribute("error", "???"); return "/login"; } return "redirect:/index.html"; }
From source file:com.parallax.server.blocklyprop.security.BlocklyPropSessionDao.java
/** * Convert a Session object into a SessionRecord object * * @param session/*from w w w. j a v a2 s . com*/ * the session to convert into a SessionRecord * * @return * a SessionRecord object containing the details necessary to persist the object * into an EIS. */ private SessionRecord convert(Session session) { LOG.trace("Converting session {} to a SessionRecord object", session.getId()); // Cast the Session parameter into a SimpleSession reference SimpleSession ssession = (SimpleSession) session; SessionRecord sessionRecord = new SessionRecord(); sessionRecord.setIdsession(session.getId().toString()); sessionRecord.setStarttimestamp(new Timestamp(session.getStartTimestamp().getTime())); sessionRecord.setLastaccesstime(new Timestamp(session.getLastAccessTime().getTime())); sessionRecord.setTimeout(session.getTimeout()); sessionRecord.setHost(session.getHost()); // Gather the session attributes into a HashMap that can be persisted into the // SessionRecord object if (ssession.getAttributes() != null) { HashMap<Object, Object> attributes = (HashMap<Object, Object>) ssession.getAttributes(); // Logging attributes // LOG.debug("Session attributes:"); // attributes.forEach( (k,v) -> LOG.debug("Key: {}, Value: {}", k, v)); sessionRecord.setAttributes(SerializationUtils.serialize(attributes)); } return sessionRecord; }