public SessionUser getSessionUser() { Subject subject = SecurityUtils.getSubject(); SessionUser sessionUser = (SessionUser) subject.getSession().getAttribute("SESSION_USER"); if (sessionUser == null) { sessionUser = (SessionUser) subject.getPrincipal(); subject.getSession().setAttribute("SESSION_USER", sessionUser); } return sessionUser; }
public Session getSession() { Session session = null; try { Subject subject = SecurityUtils.getSubject(); session = subject.getSession(false); if (session == null) { session = subject.getSession(); } } catch (InvalidSessionException e) { logger.error("Invalid session error", e); } catch (UnavailableSecurityManagerException e2) { logger.error("Unavailable SecurityManager error", e2); } return session; }
public static Session getSession() { try { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session == null) { session = subject.getSession(); } if (session != null) { return session; } } catch (InvalidSessionException e) { } return null; }
// 取得Cognos8连接 public CRNConnect getConnect() { Subject currentUser = SecurityUtils.getSubject(); CRNConnect connection = (CRNConnect) currentUser.getSession().getAttribute("connection"); return connection; }
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(); }
/** * 为当前登录的Subject授予角色和权限 * * @see 经测试:本例中该方法的调用时机为需授权资源被访问时 * @see 经测试:并且每次访问需授权资源时,只有第一次需要执行该方法,这表明本例中默认启用AuthorizationCache * @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache * @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { logger.info("------------开始 SecurityRealm doGetAuthorizationInfo----------"); // String currentUsername = (String)super.getAvailablePrincipal(arg0); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); Subject currentUser = SecurityUtils.getSubject(); Collection<String> con = (Collection) currentUser.getSession().getAttribute(IConstants.SHIRO_ROLE_INFO); for (String string : con) { // SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // System.out.println(string); simpleAuthorInfo.addStringPermission(string); // 需要访问需授权资源的时候调用该函数,且一个subject调用了该函数后,只要session还在有效期,再次访问需授权资源的时候 // 就不需要再次执行该函数了。所以产生的问题就是如果权限改变了,但是原session还有效。需要用户重新手动的执行一次登录 } return simpleAuthorInfo; // /* if(null!=currentUsername && "001".equals(currentUsername)){ // //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色 // simpleAuthorInfo.addRole("admin"); // //添加权限 // simpleAuthorInfo.addStringPermission("admin:manage111"); // logger.info("已为用户["+currentUsername+"]赋予了[admin]角色和[admin:manage]权限"); // return simpleAuthorInfo; // }*/ // // return null; }
/** 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AccountException { Subject currentUser = SecurityUtils.getSubject(); currentUser.getSession(); System.out.println("============" + this.getAuthenticationCacheName()); System.out.println("============" + this.getAuthorizationCacheName()); UsernamePasswordToken token = (UsernamePasswordToken) authcToken; ShiroUser user = null; try { user = shiroUserService.findUserByLoginName(token.getUsername()); } catch (Exception e) { e.printStackTrace(); } if (user != null) { if (!user.isEnabled()) { throw new DisabledAccountException(); } byte[] salt = EncodeUtils.hexDecode(user.getSalt()); return new SimpleAuthenticationInfo( user, user.getPassword(), ByteSource.Util.bytes(salt), getName()); } else { return null; } }
/** 获取头部信息 */ @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); }
/** 显示用户列表(用户组) */ @RequestMapping(value = "/list") public ModelAndView listappactivitys(Page page) throws Exception { logBefore(logger, "WxBindCustomerController_listusers"); ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); // 按照条件检索 try { Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Sys_User user = (Sys_User) session.getAttribute(Const.SESSION_USER); String factoryid = user.getDoc_factory().getId(); // 分页查询 String currentPage = ""; if (pd.toString().contains("currentPage")) currentPage = pd.getString("currentPage"); else currentPage = "1"; PageBean pageappactivity = appbookService.findpageappbook(factoryid, currentPage); page.setPd(pd); mv.setViewName("system/appbook/appbook_list"); mv.addObject("varList", pageappactivity.getRecordList()); pd.put("pagepicture", pageappactivity); mv.addObject("pd", pd); } catch (Exception e) { e.printStackTrace(); logger.error(e.toString(), e); } return mv; }
@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); }
@ValidateParams({ @ValidateParam(value = "user.name", minLen = 4, maxLen = 12), @ValidateParam(value = "user.password", minLen = 6, maxLen = 20), @ValidateParam(value = "captcha", defaultValue = "@@@@", maxLen = 4, minLen = 4), @ValidateParam(value = "rememberMe", type = Boolean.class) }) @RequestMethod(Method.POST) public void signin() { User user = getModel(User.class, "user"); Sys_Common_Variable captcha = ComVarService.service.getComVarByName(Key.CAPTCHA); if (captcha != null && captcha.getToBoolean(Sys_Common_Variable.S_VALUE) && !validateCaptcha(getPara("captcha"))) { renderJson(new Message(captcha.getStr(Sys_Common_Variable.S_ERROR))); return; } Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken(user.getStr(User.S_NAME), user.getStr(User.S_PASSWORD)); token.setRememberMe(getParaToBoolean("rememberMe")); subject.login(token); if (subject.isAuthenticated()) { subject.getSession().setAttribute(Lc4eCaptchaRender.captcha_code, Const.DEFAULT_NONE); } else { renderJson(new Message("Login failed")); } } renderJson(new Message(true, "Login Success")); }
@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); }
/** * 用户注销 * * @param * @return */ @RequestMapping(value = "/logout") public ModelAndView logout() { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); session.removeAttribute(Const.SESSION_USER); session.removeAttribute(Const.SESSION_ROLE_RIGHTS); session.removeAttribute(Const.SESSION_allmenuList); session.removeAttribute(Const.SESSION_menuList); session.removeAttribute(Const.SESSION_QX); session.removeAttribute(Const.SESSION_userpds); session.removeAttribute(Const.SESSION_USERNAME); session.removeAttribute(Const.SESSION_USERROL); session.removeAttribute("changeMenu"); // shiro销毁登录 // Subject subject = SecurityUtils.getSubject(); currentUser.logout(); pd = this.getPageData(); String msg = pd.getString("msg"); pd.put("msg", msg); pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 读取系统名称 mv.setViewName("system/admin/login"); mv.addObject("pd", pd); return mv; }
/** 去新增用户页面 */ @RequestMapping(value = "/goAddU") public ModelAndView goAddU() throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("USERID", user.getUSER_ID()); pd.put("ROLEID", user.getROLE_ID()); logger.info("pd:" + gson.toJson(pd)); List<Role> roleList = null; if (userService.isAdmin(user.getROLE_ID())) { roleList = roleService.listAllERRoles(); // 列出所有角色 } else if (userService.isCooper(user.getROLE_ID())) { roleList = roleService.listSubUserRole(userService.SUBUSER_CODE); // 列出所有二级角色 } mv.setViewName("system/user/user_edit"); mv.addObject("msg", "saveU"); mv.addObject("pd", pd); mv.addObject("roleList", roleList); return mv; }
/** * 根据角色id获取角色菜单关系测试方法. * * @throws Exception 普通异常. */ @Test public final void testQueryRoleMenuItemMap() throws Exception { Subject currentUser = ShiroHelper.getSubject(this.request, this.response); UsernamePasswordToken token = new UsernamePasswordToken("user1", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); token.setRememberMe(true); try { currentUser.login(token); UserPo uPo = new UserPo(); uPo.setUserId(Long.valueOf("1")); uPo.setLoginName("user1"); uPo.setPassword("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-01-12 23:30:20"); uPo.setCreateTime(date); uPo.setCreatorId(Long.valueOf("1")); uPo.setIsDelete(false); uPo.setIsLockUp(false); uPo.setVersion(Long.valueOf("0")); currentUser.getSession().setAttribute("user", uPo); } catch (Exception se) { se.printStackTrace(); } request.setParameter("roleMenuItemMap", "{\"roleId\":\"2\"}"); String resultMessage = executeAction("/SuperW/queryRoleMenuItemMap.action"); boolean rs = -1 != resultMessage.indexOf( "{\"userToken\":true,\"serviceResult\":true," + "\"resultInfo\":\"查询角色菜单关系列表成功\""); assertTrue("返回服務信息錯誤失敗", rs); }
@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; }
@RequestMapping(value = "/auth", method = POST) public void authenticate(@RequestBody final UsernamePasswordToken credentials) { log.info( "Authenticating {} with password {}", credentials.getUsername(), credentials.getPassword()); final Subject subject = SecurityUtils.getSubject(); subject.login(credentials); // set attribute that will allow session querying subject.getSession().setAttribute("email", credentials.getUsername()); }
/** * 将一些数据放到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); } } }
private void subjectLog() { Subject s = SecurityUtils.getSubject(); log.info("subject: {}", s); log.info( "hasRole? admin:{} guest:{} geek:{}", s.hasRole("admin"), s.hasRole("guest"), s.hasRole("geek")); log.info("session: {}", s.getSession()); }
/* ===============================权限================================== */ public void getHC() { ModelAndView mv = this.getModelAndView(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Map<String, String> map = (Map<String, String>) session.getAttribute(Const.SESSION_QX); mv.addObject(Const.SESSION_QX, map); // 按钮权限 List<Menu> menuList = (List) session.getAttribute(Const.SESSION_menuList); mv.addObject(Const.SESSION_menuList, menuList); // 菜单权限 }
/** 显示用户列表(用户组) */ @RequestMapping(value = "/listUsers") public ModelAndView listUsers(Page page) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); String USERNAME = pd.getString("USERNAME"); if (null != USERNAME && !"".equals(USERNAME)) { USERNAME = USERNAME.trim(); pd.put("USERNAME", USERNAME); } String lastLoginStart = pd.getString("lastLoginStart"); String lastLoginEnd = pd.getString("lastLoginEnd"); if (lastLoginStart != null && !"".equals(lastLoginStart)) { lastLoginStart = lastLoginStart + " 00:00:00"; pd.put("lastLoginStart", lastLoginStart); } if (lastLoginEnd != null && !"".equals(lastLoginEnd)) { lastLoginEnd = lastLoginEnd + " 00:00:00"; pd.put("lastLoginEnd", lastLoginEnd); } // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("USERID", user.getUSER_ID()); pd.put("ROLEID", user.getROLE_ID()); logger.info("pd:" + gson.toJson(pd)); page.setPd(pd); List<PageData> userList = null; List<Role> roleList = null; if (userService.isAdmin(user.getROLE_ID())) { userList = userService.listPdPageUser(page); // 列出用户列表 roleList = roleService.listAllERRoles(); // 列出所有角色 } else if (userService.isCooper(user.getROLE_ID())) { userList = userService.listSubUser(page); // 列出用户列表 roleList = roleService.listSubUserRole(userService.SUBUSER_CODE); // 列出所有二级角色 } mv.setViewName("system/user/user_list"); mv.addObject("userList", userList); mv.addObject("roleList", roleList); mv.addObject("pd", pd); mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限 return mv; }
@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()); }
/** * 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()); }
protected static Member getLoginUser(boolean returnRemembered) { Subject subject = SecurityUtils.getSubject(); if (subject == null) { return null; } Session session = subject.getSession(); if (session == null) { if (subject.isRemembered() == true) { return (Member) subject.getPrincipal(); } return null; } return (Member) session.getAttribute(Constants.CURRENT_USER); }
/** * @方法名: 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; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { SessionIdToken sessionIdToken = (SessionIdToken) token; final Subject subject = new Subject.Builder().sessionId(sessionIdToken.getSessionId()).buildSubject(); final Session session = subject.getSession(false); if (session == null) { LOG.debug( "Invalid session {}. Either it has expired or did not exist.", sessionIdToken.getSessionId()); return null; } final Object username = subject.getPrincipal(); final User user = userService.load(String.valueOf(username)); if (user == null) { LOG.debug("No user named {} found for session {}", username, sessionIdToken.getSessionId()); return null; } if (user.isExternalUser() && !ldapAuthenticator.isEnabled()) { throw new LockedAccountException("LDAP authentication is currently disabled."); } if (LOG.isDebugEnabled()) { LOG.debug("Found session {} for user name {}", session.getId(), username); } @SuppressWarnings("unchecked") final MultivaluedMap<String, String> requestHeaders = (MultivaluedMap<String, String>) ThreadContext.get("REQUEST_HEADERS"); // extend session unless the relevant header was passed. if (requestHeaders == null || !"true".equalsIgnoreCase(requestHeaders.getFirst("X-Graylog-No-Session-Extension"))) { session.touch(); } else { LOG.debug("Not extending session because the request indicated not to."); } ThreadContext.bind(subject); return new SimpleAccount(user.getName(), null, "session authenticator"); }
/** 保存皮肤 */ @RequestMapping(value = "/setSKIN") public void setSKIN(PrintWriter out) { PageData pd = new PageData(); try { pd = this.getPageData(); // shiro管理的session Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString(); // 获取当前登录者loginname pd.put("USERNAME", USERNAME); userService.setSKIN(pd); session.removeAttribute(Const.SESSION_userpds); session.removeAttribute(Const.SESSION_USERROL); out.write("success"); out.close(); } catch (Exception e) { logger.error(e.toString(), e); } }
/** * 用户主页 * * @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"; }
/** 保存用户 */ @RequestMapping(value = "/saveU") public ModelAndView saveU(PrintWriter out) throws Exception { ModelAndView mv = this.getModelAndView(); PageData pd = new PageData(); pd = this.getPageData(); pd.put("USER_ID", this.get32UUID()); // ID pd.put("RIGHTS", ""); // 权限 pd.put("LAST_LOGIN", ""); // 最后登录时间 pd.put("IP", ""); // IP pd.put("STATUS", "0"); // 状态 pd.put("SKIN", "default"); // 默认皮肤 // 从session获取用户信息 Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); User user = (User) session.getAttribute(Const.SESSION_USER); pd.put("CREATOR", user.getUSER_ID()); logger.info("pd:" + gson.toJson(pd)); pd.put( "PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString()); if (null == userService.findByUId(pd)) { if (Jurisdiction.buttonJurisdiction(menuUrl, "add")) { userService.saveU(pd); } // 判断新增权限 mv.addObject("msg", "success"); } else { mv.addObject("msg", "failed"); } mv.setViewName("save_result"); return mv; }
/** * 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) { } }