Java Code Examples for org.apache.shiro.session.Session#setAttribute()
The following examples show how to use
org.apache.shiro.session.Session#setAttribute() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserServiceImpl.java From axelor-open-suite with GNU Affero General Public License v3.0 | 6 votes |
@Override @Transactional(rollbackOn = {AxelorException.class, Exception.class}) public void generateRandomPasswordForUsers(List<Long> userIds) { AuthService authService = Beans.get(AuthService.class); LocalDateTime todayDateTime = Beans.get(AppBaseService.class).getTodayDateTime().toLocalDateTime(); for (Long userId : userIds) { User user = userRepo.find(userId); String password = this.generateRandomPassword().toString(); user.setTransientPassword(password); password = authService.encrypt(password); user.setPassword(password); user.setPasswordUpdatedOn(todayDateTime); userRepo.save(user); } // Update login date in session so that user changing own password doesn't get logged out. if (userIds.contains(getUserId())) { Session session = AuthUtils.getSubject().getSession(); session.setAttribute("loginDate", todayDateTime); } }
Example 2
Source File: SessionRegeneratingFilter.java From seed with Mozilla Public License 2.0 | 6 votes |
/** * Regenerate the session if any. This prevents a potential session fixation issue by forcing a new session id on * login success. See https://issues.apache.org/jira/browse/SHIRO-170. * * @param subject the successfully logged in subject */ default void regenerateSession(Subject subject) { Session session = subject.getSession(false); if (session != null) { // Retain session attributes Map<Object, Object> attributes = new LinkedHashMap<>(); for (Object key : session.getAttributeKeys()) { Object value = session.getAttribute(key); if (value != null) { attributes.put(key, value); } } // Destroy the current sessions and recreate a new one session.stop(); session = subject.getSession(true); // Restore attributes in the new session for (Map.Entry<Object, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } } }
Example 3
Source File: FormAuthenticationCaptchaFilter.java From cms with Apache License 2.0 | 6 votes |
@Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { Session session = SecurityUtils.getSubject().getSession(); //获取登录错误次数 Integer number = (Integer) session.getAttribute(getLoginIncorrectNumberKeyAttribute()); //首次登录,将该数量记录在session中 if (number == null) { number = 1; session.setAttribute(getLoginIncorrectNumberKeyAttribute(), number); } //如果登录次数大于allowIncorrectNumber,需要判断验证码是否一致 if (number > getAllowIncorrectNumber()) { //获取当前验证码 String currentCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY); //获取用户输入的验证码 String submitCaptcha = getCaptcha(request); //如果验证码不匹配,登录失败 if (StringUtils.isEmpty(submitCaptcha) || !StringUtils.equals(currentCaptcha, submitCaptcha.toLowerCase())) { return onLoginFailure(this.createToken(request, response), new CaptchaException(), request, response); } } return super.executeLogin(request, response); }
Example 4
Source File: CentralAuthenticationHandler.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Puts grantCredentials to session. </br> * * @param session * Session * @param grantAppname * granting application name * @param grant * grant ticket */ private void putGrantCredentials(Session session, String grantAppname, GrantApp grant) { notNullOf(session, "session"); hasTextOf(grantAppname, "grantAppname"); notNullOf(grant, "grant"); /** * @See {@link CentralAuthenticationHandler#validate()} */ GrantCredentialsInfo info = getGrantCredentials(session); if (info.has(grantAppname)) { log.debug("Sets grantTicket of sessionId: {} grantAppname: {}", session.getId(), grantAppname); } // Updating grantTicket. session.setAttribute(new RelationAttrKey(KEY_GRANTCREDENTIALS), info.putGrant(grantAppname, grant)); log.debug("Updated granting credentials to session. {}", info); // Sets grantTicket => sessionId. /** * @see {@link com.wl4g.devops.iam.client.validation.FastCasTicketIamValidator#validate()} * @see {@link com.wl4g.devops.iam.common.session.mgt.AbstractIamSessionManager#getSessionId()} */ long expireTime = getSessionRemainingTime(session); // Expiration time cacheManager.getIamCache(CACHE_TICKET_S).put(new CacheKey(grant.getGrantTicket(), expireTime), valueOf(session.getId())); log.debug("Sets grantTicket: '{}' of seesionId: '{}', expireTime: '{}'", grant, getSessionId(session), expireTime); }
Example 5
Source File: ShiroRealm.java From Spring-Shiro-Spark with Apache License 2.0 | 6 votes |
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String userName = token.getUsername(); User user = userDao.findUserByUsername(userName); UserDto userDto = convertToDto(user); if(user != null){ //登陆成功 Session session = SecurityUtils.getSubject().getSession(); session.setAttribute("user",userDto); session.setAttribute("id",user.getId()); session.setAttribute("username",user.getUsername()); session.setAttribute("name",user.getName()); return new SimpleAuthenticationInfo( userName, //用户 user.getPassword(), //密码 getName() //realm name ); } else { throw new UnknownAccountException(); } }
Example 6
Source File: ShiroUtils.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 5 votes |
/** * 强制退出 * * @param sessionId * 退出的sessionId */ public static boolean forceLogout(String sessionId) { try { Session session = shiroConfig().getSessionManager().getSession(new DefaultSessionKey(sessionId)); if (session != null) { session.setAttribute(ShiroProperties.ATTRIBUTE_SESSION_FORCE_LOGOUT, Boolean.TRUE); } return Boolean.TRUE; } catch (UnknownSessionException e) { LOGGER.warn(e.getMessage(), e); } return Boolean.FALSE; }
Example 7
Source File: RoleController.java From Mario with Apache License 2.0 | 5 votes |
/** * 重置User的Menu信息 */ private void resetUserMenu() { Subject currentUser = SecurityUtils.getSubject(); ShiroUser user = (ShiroUser) currentUser.getPrincipal(); Session session = currentUser.getSession(); List<Menu> menus = accountService.findMenuByUserID(user.getId()); session.setAttribute("menuList", menus); }
Example 8
Source File: SessionUtil.java From spring-boot-seed with MIT License | 5 votes |
/** * 存储参数到Session * * @param key 存储的key * @param value 存储的value */ public static void setAttribute(String key, Object value) { Session session = getCurrentSession(); if (session != null) { session.setAttribute(key, value); } }
Example 9
Source File: CaptchaAuthenticationFilter.java From base-framework with Apache License 2.0 | 5 votes |
/** * 重写父类方法,在shiro执行登录时先对比验证码,正确后在登录,否则直接登录失败 */ @Override protected boolean executeLogin(ServletRequest request,ServletResponse response) throws Exception { Session session = getSubject(request, response).getSession(); //获取登录次数 Integer number = (Integer) session.getAttribute(getLoginNumKeyAttribute()); //首次登录,将该数量记录在session中 if (number == null) { number = new Integer(1); session.setAttribute(getLoginNumKeyAttribute(), number); } //如果登录次数大于allowLoginNum,需要判断验证码是否一致 if (number > getAllowLoginNum()) { //获取当前验证码 String currentCaptcha = (String) session.getAttribute(getSessionCaptchaKeyAttribute()); //获取用户输入的验证码 String submitCaptcha = getCaptcha(request); //如果验证码不匹配,登录失败 if (StringUtils.isEmpty(submitCaptcha) || !StringUtils.equals(currentCaptcha,submitCaptcha.toLowerCase())) { return onLoginFailure(this.createToken(request, response), new AccountException("验证码不正确"), request, response); } } return super.executeLogin(request, response); }
Example 10
Source File: ShiroService.java From VideoMeeting with Apache License 2.0 | 5 votes |
/** * 将一些数据放到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); } } }
Example 11
Source File: SessionInterceptor.java From ZTuoExchange_framework with MIT License | 5 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); AdminService adminService = (AdminService) factory.getBean("adminService"); System.out.println(request.getContextPath()); Subject currentUser = SecurityUtils.getSubject(); //判断用户是通过记住我功能自动登录,此时session失效 if(!currentUser.isAuthenticated() && currentUser.isRemembered()){ try { Admin admin = adminService.findByUsername(currentUser.getPrincipals().toString()); //对密码进行加密后验证 UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword(),currentUser.isRemembered()); //把当前用户放入session currentUser.login(token); Session session = currentUser.getSession(); session.setAttribute(SysConstant.SESSION_ADMIN,admin); //设置会话的过期时间--ms,默认是30分钟,设置负数表示永不过期 session.setTimeout(30*60*1000L); }catch (Exception e){ //自动登录失败,跳转到登录页面 //response.sendRedirect(request.getContextPath()+"/system/employee/sign/in"); ajaxReturn(response, 4000, "unauthorized"); return false; } if(!currentUser.isAuthenticated()){ //自动登录失败,跳转到登录页面 ajaxReturn(response, 4000, "unauthorized"); return false; } } return true; }
Example 12
Source File: CaptchaAuthenticationFilter.java From base-framework with Apache License 2.0 | 5 votes |
/** * 重写父类方法,当登录成功后,将allowLoginNum(允许登录次)设置为0,重置下一次登录的状态 */ @Override protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { Session session = subject.getSession(false); session.removeAttribute(getLoginNumKeyAttribute()); session.removeAttribute(getSessionShowCaptchaKeyAttribute()); session.setAttribute("sv", subject.getPrincipal()); return super.onLoginSuccess(token, subject, request, response); }
Example 13
Source File: LoginController.java From dpCms with Apache License 2.0 | 5 votes |
/** * 获取登录的图片验证码 */ @RequestMapping(value = "/imgcode", method = RequestMethod.GET) public void captcha(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); Producer captchaProducer = KaptchaProducerAgency.getKaptchaProducerExample(); response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // return a jpeg response.setContentType("image/jpeg"); // create the text for the image String capText = captchaProducer.createText(); log.debug("******************验证码是: " + capText + "******************"); // store the text in the session session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText ); // create the image with the text BufferedImage bi = captchaProducer.createImage(capText); ServletOutputStream out = response.getOutputStream(); // write the data out ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } }
Example 14
Source File: UserOnlineServiceImpl.java From belling-admin with Apache License 2.0 | 5 votes |
@Override public void kickoutByAccount(String account) { if (Strings.isNullOrEmpty(account)) return; Collection<Session> sessions = sessionDAO.getActiveSessions(); if (sessions.size() <= 0) return; System.out.println("kickoutByAccount sessions size is :" + sessions.size()); for(Session session : sessions){ Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY); if (obj != null) { String tempName = obj.toString(); if (account.equals(tempName)) { // 会话已失效 但在线列表仍可获取Session会话对象 session.setAttribute("kickout", true); // 标记为已下线 session.setTimeout(0L); //设置session立即失效,即将其踢出系统break; // session.stop(); //销毁Shiro的会话 // 记录日志 LoginLog log = new LoginLog(); log.setUserId(account); log.setLoginType((short) 1); log.setLoginDesc("账号异地登录,被迫强制下线"); log.setIpInfoCountry(null); log.setIpInfoRegion(null); log.setIpInfoCity(null); log.setIpInfoIsp(null); log.setLoginIp(RequestUtil.getAddr(RequestUtil.getRequest())); log.setLoginTime(new Timestamp(new Date().getTime())); // 保存退出日志 loginLogMapper.insert(log); break; } } } }
Example 15
Source File: ShiroDBRealm.java From tianti with Apache License 2.0 | 5 votes |
/** * * @param key * @param value */ private void setSession(Object key, Object value){ Subject subject = SecurityUtils.getSubject(); if(subject != null){ Session session = subject.getSession(); if(session != null){ session.setAttribute(key, value); } } }
Example 16
Source File: AdminRealm.java From ZTuoExchange_framework with MIT License | 5 votes |
/** * 将一些数据放到ShiroSession中,以便于其它地方使用 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 * * @param key * @param value */ private void setSession(Object key, Object value) { Subject currentUser = SecurityUtils.getSubject(); if (null != currentUser) { Session session = currentUser.getSession(); session.setTimeout(1800000L); log.info("Session默认超时时间为[" + session.getTimeout() + "]毫秒"); if (null != session) { session.setAttribute(key, value); } } }
Example 17
Source File: Main.java From java-course-ee with MIT License | 4 votes |
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(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log("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("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log("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("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log("May the Schwartz be with you!"); } else { log("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log("You may use a lightsaber ring. Use it wisely."); } else { log("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
Example 18
Source File: StandaloneShiroTest.java From attic-polygene-java with Apache License 2.0 | 4 votes |
@Test public void test() { // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute( "someKey", "aValue" ); String value = ( String ) session.getAttribute( "someKey" ); assertEquals( "aValue", value ); 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 ) { fail( "There is no user with username of " + token.getPrincipal() ); } catch ( IncorrectCredentialsException ice ) { fail( "Password for account " + token.getPrincipal() + " was incorrect!" ); } catch ( LockedAccountException lae ) { fail( "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? throw ae; } } //say who they are: //print their identifying principal (in this case, a username): assertNotNull( currentUser.getPrincipal() ); LOG.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." ); //test a role: if ( currentUser.hasRole( "schwartz" ) ) { LOG.info( "May the Schwartz be with you!" ); } else { fail( "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 { fail( "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 { fail( "Sorry, you aren't allowed to drive the 'eagle5' winnebago!" ); } //all done - log out! currentUser.logout(); }
Example 19
Source File: ShiroKit.java From SpringBootBucket with MIT License | 4 votes |
/** * 设置shiro指定的sessionKey */ public static void setSessionAttr(String key, Object value) { Session session = getSession(); session.setAttribute(key, value); }
Example 20
Source File: ShiroTutorial.java From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International | 4 votes |
public static void main(String[] args) { log.info("My First Apache Shiro Application"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-app.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if ("aValue".equals(value)) { 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!"); } // all done - log out! currentUser.logout(); System.exit(0); }