// Do some stuff with a Session (no need for a web or EJB container!!!)
//2. 通过当前用户拿到session Sessionsession= currentUser.getSession(); session.setAttribute("someKey", "aValue"); Stringvalue= (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: //3. 判断当前的用户是被认证 if (!currentUser.isAuthenticated()) { UsernamePasswordTokentoken=newUsernamePasswordToken("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: //4. 测试当前用户是否有角色 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:wield")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //细粒度 /** * 这些权限都是在shiro.ini中的 * admin = * * schwartz = lightsaber:* * goodguy = winnebago:drive:eagle5 */ //是否拥有更高的权限 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!"); }