/** 获取头部信息 */ @RequestMapping(value = "/getUname") @ResponseBody public Object getList() { PageData pd = new PageData(); Map<String, Object> map = new HashMap<String, Object>(); try { pd = this.getPageData(); List<PageData> pdList = new ArrayList<PageData>(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); PageData pds = new PageData(); pds = (PageData) session.getAttribute(Const.SESSION_userpds); if (null == pds) { String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString(); // 获取当前登录者loginname pd.put("USERNAME", USERNAME); pds = userService.findByUId(pd); session.setAttribute(Const.SESSION_userpds, pds); } pdList.add(pds); map.put("list", pdList); } catch (Exception e) { logger.error(e.toString(), e); } finally { logAfter(logger); } return AppUtil.returnObject(pd, map); }
/** * store data to shiro session * * @param key data's key * @param value data's value */ public static void store(Object key, Object value) { Session session = getSession(); session.setAttribute(key, value); if (logger.isDebugEnabled()) { logger.debug("session timeout default {} s", session.getTimeout() / 1000); } }
@RequestMapping("/login") public ModelAndView login( HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password, Boolean isRemeberMe) throws Exception { UsernamePasswordToken token = new UsernamePasswordToken(userName, password); Subject subject = SecurityUtils.getSubject(); subject.login(token); if (null != isRemeberMe && isRemeberMe) token.setRememberMe(true); if (subject.isAuthenticated()) { AuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, userName); Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = new User(); user.setUserName(userName); user.setPassword(password); Env env = new Env(); env.setUser(user); session.setAttribute("env", env); GlobalConfigHolder.setEnv(env); ModelAndView view = createLayoutView("admin/index", request, response); return view; } else return createSingleView("login/login", request, response); }
public static String randomUUID(HttpServletRequest request) { Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Object uuid = session.getAttribute("UUID"); session.setAttribute("UUID", UUID.randomUUID().toString()); return uuid == null ? "" : uuid.toString(); }
@Override public boolean isAccessAllowed( ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); // 如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true // 证明是没登陆直接通过记住我功能进来的 if (!subject.isAuthenticated() && subject.isRemembered()) { // 获取session看看是不是空的 Session session = subject.getSession(true); // 随便拿session的一个属性来看session当前是否是空的,我用userId,你们的项目可以自行发挥 if (session.getAttribute(SessionObject.SESSION_KEY) == null) { // 如果是空的才初始化,否则每次都要初始化,项目得慢死 // 这边根据前面的前提假设,拿到的是username String username = subject.getPrincipal().toString(); // 在这个方法里面做初始化用户上下文的事情,比如通过查询数据库来设置session值,你们自己发挥 User user = userService.get(Long.parseLong(username)); UsernamePasswordToken token = new UsernamePasswordToken(user.getId().toString(), user.getPassword(), true); SecurityUtils.getSubject().login(token); SessionObject so = new SessionObject(); so.setUser(user); session.setAttribute(SessionObject.SESSION_KEY, so); } } // 这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() // 让它同时也兼容remember这种情况 return super.isAccessAllowed(request, response, mappedValue); }
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (!subject.isAuthenticated() && !subject.isRemembered()) { // 如果没有登录,直接进行之后的流程 return true; } Session session = subject.getSession(); // String username = (String) subject.getPrincipal(); String account = ((ShiroUser) subject.getPrincipal()).getAccount(); Serializable sessionId = session.getId(); // TODO 同步控制 Deque<Serializable> deque = cache.get(account); if (deque == null) { deque = new LinkedList<Serializable>(); cache.put(account, deque); } // 如果队列里没有此sessionId,且用户没有被踢出;放入队列 if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) { deque.push(sessionId); } // 如果队列里的sessionId数超出最大会话数,开始踢人 while (deque.size() > maxSession) { Serializable kickoutSessionId = null; if (kickoutAfter) { // 如果踢出后者 kickoutSessionId = deque.removeFirst(); } else { // 否则踢出前者 kickoutSessionId = deque.removeLast(); } try { Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId)); if (kickoutSession != null) { // 设置会话的kickout属性表示踢出了 kickoutSession.setAttribute("kickout", true); } } catch (Exception e) { // ignore exception } } // 如果被踢出了,直接退出,重定向到踢出后的地址 if (session.getAttribute("kickout") != null) { // 会话被踢出了 try { subject.logout(); } catch (Exception e) { // ignore } saveRequest(request); WebUtils.issueRedirect(request, response, kickoutUrl); return false; } return true; }
/** * 将一些数据放到ShiroSession中,以便于其它地方使用 * * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 */ private void setSession(Object key, Object value) { Subject currentUser = SecurityUtils.getSubject(); if (null != currentUser) { Session session = currentUser.getSession(); System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒"); if (null != session) { session.setAttribute(key, value); } } }
@RequestMapping( value = "/list/{p}", method = {RequestMethod.GET, RequestMethod.POST}) public String linkList( Link link, @PathVariable Integer p, HttpServletRequest request, ModelMap modelMap) { Session session = SystemUtils.getShiroSession(); if (StringUtils.isNotBlank(link.getLinkName())) { session.setAttribute("linkSearch", link); modelMap.addAttribute("searchLink", link); } else { session.setAttribute("linkSearch", null); } Object searchObj = session.getAttribute("linkSearch"); Page<Link> result = linkService.findLinkPageable((searchObj == null ? (new Link()) : ((Link) searchObj)), p); modelMap.addAttribute("links", result.getContent()); modelMap.addAttribute( "pagination", SystemUtils.pagination(result, HttpUtils.getContextPath(request) + "/manager/link/list")); return "link/link_list"; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; User user = userService.findByUserName(token.getUsername()); Session session = SecurityUtils.getSubject().getSession(); if (user == null) { throw new AuthorizationException("用户不存在"); } SimpleAuthenticationInfo info = null; if (user.getUsername().equals(token.getUsername())) { info = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); session.setAttribute("user", user); } return info; }
/** * @方法名: getAllMenu @功能描述: 获取所有菜单 * * @param userId * @return @作者 zlt @日期 2016年7月18日 */ @RequestMapping(value = "/getAllMenu", method = RequestMethod.POST) @ResponseBody public String getAllMenu(SysMenu sysMenu) { log.debug("获取所有菜单"); List<SysMenu> rows; JSONObject obj = new JSONObject(); String result = ""; try { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); List<SysMenu> allmenuList = new ArrayList<SysMenu>(); String roleRights = ""; if (null == session.getAttribute(Const.SESSION_allmenuList)) { allmenuList = sysMenuService.selectAllMenu(sysMenu); if (StringUtil.isNullOrEmpty(roleRights)) { for (SysMenu menu : allmenuList) { // menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMenuId())); menu.setHasMenu(true); if (menu.isHasMenu()) { List<SysMenu> subMenuList = menu.getSubMenu(); for (SysMenu sub : subMenuList) { // sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMenuId())); sub.setHasMenu(true); } } } } session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中 } else { allmenuList = (List<SysMenu>) session.getAttribute(Const.SESSION_allmenuList); } result = JSONObject.toJSONString( allmenuList, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty); } catch (Exception e) { log.error("获取所有菜单出错", e); } System.out.println(result); return result; }
@Test public void testDefaultConfig() { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("guest", "guest"); subject.login(token); assertTrue(subject.isAuthenticated()); assertTrue("guest".equals(subject.getPrincipal())); assertTrue(subject.hasRole("guest")); Session session = subject.getSession(); session.setAttribute("key", "value"); assertEquals(session.getAttribute("key"), "value"); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setContentType("image/png"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); try { Session session = SecurityUtils.getSubject().getSession(); String token = EncoderHelper.getChallangeAndWriteImage(captchaService, "png", res.getOutputStream()); session.removeAttribute(KEY_CAPTCHA); session.setAttribute(KEY_CAPTCHA, token); } catch (Exception e) { e.printStackTrace(); } }
/** 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { ShiroEmp shiroEmp = (ShiroEmp) principals.getPrimaryPrincipal(); EosEmp eosEmp = eosEmpService.findByEno(shiroEmp.loginName); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); /* 系统不使用角色 */ /* * List<String> resourceList = * eosEmpService.getAllRoleAction(eosEmp.getRoleId()); * info.addStringPermissions(resourceList); String roleName = * eosRoleService.getRoleName(eosEmp.getRoleId()); * info.addRole(roleName); */ Session session = SecurityUtils.getSubject().getSession(); session.setAttribute("eosEmp", eosEmp); return info; }
/** * 用户主页 * * @param model * @return */ @RequestMapping(value = "/home", method = RequestMethod.GET) public String home(Model model) { Subject subject = SecurityUtils.getSubject(); ShiroUser shiroUser = (ShiroUser) subject.getPrincipal(); User user = userService.get(shiroUser.id); model.addAttribute("user", user); Session session = subject.getSession(true); session.setAttribute(CommonStatus.SESSION_USER_NAME, user); // TODO 和大龙协商前台实现 // 用户需初始化密码 /* if (user.getFlag() == AccountContent.FLAG_PWD_INITIALIZE) { return "account/initPwd"; } */ // 个人用户 if (user.getUserType() == AccountContent.TYPE_USER) { // return "person/basicmessage/PersonalUserInfo"; // return "person/basicmessage/PersonalUserInfo2"; return "redirect:/home/user/info2"; } // 商家用户 else if (user.getUserType() == AccountContent.TYPE_BUSINESS) { return "business/index/index"; } // 代理商用户 else if (user.getUserType() == AccountContent.TYPE_PROXY) { if (user.getFlag() == AccountContent.FLAG_AUDIT) { model.addAttribute("message", "尊敬的零彩宝用户,您申请的代理商账户正在审核中,请您耐心等待!"); return "proxy/error"; } else { return "proxy/myAccount"; } } return "unknow"; }
/** * Test that validates functionality for issue <a * href="https://issues.apache.org/jira/browse/JSEC-22">JSEC-22</a> */ @Test public void testSubjectReuseAfterLogout() { Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("guest", "guest"); subject.login(token); assertTrue(subject.isAuthenticated()); assertTrue("guest".equals(subject.getPrincipal())); assertTrue(subject.hasRole("guest")); Session session = subject.getSession(); Serializable firstSessionId = session.getId(); session.setAttribute("key", "value"); assertEquals(session.getAttribute("key"), "value"); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); subject.login(new UsernamePasswordToken("lonestarr", "vespa")); assertTrue(subject.isAuthenticated()); assertTrue("lonestarr".equals(subject.getPrincipal())); assertTrue(subject.hasRole("goodguy")); assertNotNull(subject.getSession()); assertFalse(firstSessionId.equals(subject.getSession().getId())); subject.logout(); assertNull(subject.getSession(false)); assertNull(subject.getPrincipal()); assertNull(subject.getPrincipals()); }
/** * Test that validates functionality for issue <a * href="https://issues.apache.org/jira/browse/JSEC-46">JSEC-46</a> */ @Test public void testAutoCreateSessionAfterInvalidation() { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); Serializable origSessionId = session.getId(); String key = "foo"; String value1 = "bar"; session.setAttribute(key, value1); assertEquals(value1, session.getAttribute(key)); // now test auto creation: session.setTimeout(50); try { Thread.sleep(150); } catch (InterruptedException e) { // ignored } try { session.setTimeout(AbstractValidatingSessionManager.DEFAULT_GLOBAL_SESSION_TIMEOUT); fail("Session should have expired."); } catch (ExpiredSessionException expected) { } }
/** 认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { // log.info("shiro authentication"); CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authcToken; User user = userService.findByUserName( token.getUsername()); // User [loginName=a, password=a, name=管理员1, status=1] Session session = SecurityUtils.getSubject().getSession(); if (user != null) { if ("0".equals(user.getStatus())) { throw new DisabledAccountException(); } String psw = String.valueOf(token.getPassword()); if (!psw.equals(user.getPassword())) { throw new IncorrectPasswordException("密码错误!"); } session.setAttribute("user", user); return new SimpleAuthenticationInfo( new ShiroUser(user.getLoginName(), user.getName()), user.getPassword(), getName()); } else { throw new UserNotExistException("用户不存在!"); } }
/** 访问系统首页 */ @RequestMapping(value = "/main/{changeMenu}") public ModelAndView login_index(@PathVariable("changeMenu") String changeMenu) { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); try { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); if (user != null) { User userr = (User) session.getAttribute(Const.SESSION_USERROL); if (null == userr) { user = userService.getUserAndRoleById(user.getUSER_ID()); session.setAttribute(Const.SESSION_USERROL, user); } else { user = userr; } Role role = user.getRole(); String roleRights = role != null ? role.getRIGHTS() : ""; // 避免每次拦截用户操作时查询数据库,以下将用户所属角色权限、用户权限限都存入session session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); // 将角色权限存入session session.setAttribute(Const.SESSION_USERNAME, user.getUSERNAME()); // 放入用户名 List<Menu> allmenuList = new ArrayList<Menu>(); if (null == session.getAttribute(Const.SESSION_allmenuList)) { allmenuList = menuService.listAllMenu(); if (Tools.notEmpty(roleRights)) { for (Menu menu : allmenuList) { menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMENU_ID())); if (menu.isHasMenu()) { List<Menu> subMenuList = menu.getSubMenu(); for (Menu sub : subMenuList) { sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMENU_ID())); } } } } session.setAttribute(Const.SESSION_allmenuList, allmenuList); // 菜单权限放入session中 } else { allmenuList = (List<Menu>) session.getAttribute(Const.SESSION_allmenuList); } // 切换菜单===== List<Menu> menuList = new ArrayList<Menu>(); // if(null == session.getAttribute(Const.SESSION_menuList) || // ("yes".equals(pd.getString("changeMenu")))){ if (null == session.getAttribute(Const.SESSION_menuList) || ("yes".equals(changeMenu))) { List<Menu> menuList1 = new ArrayList<Menu>(); List<Menu> menuList2 = new ArrayList<Menu>(); // 拆分菜单 for (int i = 0; i < allmenuList.size(); i++) { Menu menu = allmenuList.get(i); if ("1".equals(menu.getMENU_TYPE())) { menuList1.add(menu); } else { menuList2.add(menu); } } session.removeAttribute(Const.SESSION_menuList); if ("2".equals(session.getAttribute("changeMenu"))) { session.setAttribute(Const.SESSION_menuList, menuList1); session.removeAttribute("changeMenu"); session.setAttribute("changeMenu", "1"); menuList = menuList1; } else { session.setAttribute(Const.SESSION_menuList, menuList2); session.removeAttribute("changeMenu"); session.setAttribute("changeMenu", "2"); menuList = menuList2; } } else { menuList = (List<Menu>) session.getAttribute(Const.SESSION_menuList); } // 切换菜单===== if (null == session.getAttribute(Const.SESSION_QX)) { session.setAttribute(Const.SESSION_QX, this.getUQX(session)); // 按钮权限放到session中 } // FusionCharts 报表 // String strXML = "<graph caption='前12个月订单销量柱状图' xAxisName='月份' yAxisName='值' // decimalPrecision='0' formatNumberScale='0'><set name='2013-05' value='4' // color='AFD8F8'/><set name='2013-04' value='0' color='AFD8F8'/><set name='2013-03' // value='0' color='AFD8F8'/><set name='2013-02' value='0' color='AFD8F8'/><set // name='2013-01' value='0' color='AFD8F8'/><set name='2012-01' value='0' // color='AFD8F8'/><set name='2012-11' value='0' color='AFD8F8'/><set name='2012-10' // value='0' color='AFD8F8'/><set name='2012-09' value='0' color='AFD8F8'/><set // name='2012-08' value='0' color='AFD8F8'/><set name='2012-07' value='0' // color='AFD8F8'/><set name='2012-06' value='0' color='AFD8F8'/></graph>" ; // mv.addObject("strXML", strXML); // FusionCharts 报表 // 读取websocket配置 String strWEBSOCKET = Tools.readTxtFile(Const.WEBSOCKET); // 读取WEBSOCKET配置 if (null != strWEBSOCKET && !"".equals(strWEBSOCKET)) { String strIW[] = strWEBSOCKET.split(",fh,"); if (strIW.length == 4) { pd.put("WIMIP", strIW[0]); pd.put("WIMPORT", strIW[1]); pd.put("OLIP", strIW[2]); pd.put("OLPORT", strIW[3]); } } // 读取websocket配置 mv.setViewName("system/admin/index"); mv.addObject("user", user); mv.addObject("menuList", menuList); } else { mv.setViewName("system/admin/login"); // session失效后跳转登录页面 } } catch (Exception e) { mv.setViewName("system/admin/login"); logger.error(e.getMessage(), e); } pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称 mv.addObject("pd", pd); return mv; }
/** 请求登录,验证用户 */ @RequestMapping(value = "/login_login", produces = "application/json;charset=UTF-8") @ResponseBody public Object login() throws Exception { Map<String, String> map = new HashMap<String, String>(); PageData pd = new PageData(); pd = this.getPageData(); String errInfo = ""; String KEYDATA[] = pd.getString("KEYDATA").split(",fh,"); if (null != KEYDATA && KEYDATA.length == 3) { // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); String sessionCode = (String) session.getAttribute(Const.SESSION_SECURITY_CODE); // 获取session中的验证码 String code = KEYDATA[2]; if (null == code || "".equals(code)) { errInfo = "nullcode"; // 验证码为空 } else { String USERNAME = KEYDATA[0]; String PASSWORD = KEYDATA[1]; pd.put("USERNAME", USERNAME); if (Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code)) { String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString(); // 密码加密 pd.put("PASSWORD", passwd); pd = userService.getUserByNameAndPwd(pd); if (pd != null) { pd.put("LAST_LOGIN", DateUtil.getTime().toString()); userService.updateLastLogin(pd); User user = new User(); user.setUSER_ID(pd.getString("USER_ID")); user.setUSERNAME(pd.getString("USERNAME")); user.setPASSWORD(pd.getString("PASSWORD")); user.setNAME(pd.getString("NAME")); user.setRIGHTS(pd.getString("RIGHTS")); user.setROLE_ID(pd.getString("ROLE_ID")); user.setLAST_LOGIN(pd.getString("LAST_LOGIN")); user.setIP(pd.getString("IP")); user.setSTATUS(pd.getString("STATUS")); session.setAttribute(Const.SESSION_USER, user); session.removeAttribute(Const.SESSION_SECURITY_CODE); // shiro加入身份验证 Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD); try { subject.login(token); } catch (AuthenticationException e) { errInfo = "身份验证失败!"; } } else { errInfo = "usererror"; // 用户名或密码有误 } } else { errInfo = "codeerror"; // 验证码输入有误 } if (Tools.isEmpty(errInfo)) { errInfo = "success"; // 验证成功 } } } else { errInfo = "error"; // 缺少参数 } map.put("result", errInfo); return AppUtil.returnObject(new PageData(), map); }