1 环境搭建
2 Shiro的HelloWorld
shiro-root-1.3.2-source-release\shiro-root-1.3.2\samples\quickstart
3 创建工程
4 介绍
// 获取当前的Subject,调用SecurityUtils.getSubject();
Subject currentUser = SecurityUtils.getSubject();
//测试使用Session
Session session = currentUser.getSession();
// 测试当前的用户是否已经被认证,即是否已经登录。
// 调动Subject的isAuthenticated()方法
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装成 UsernamePasswordToken对象
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
//执行登录
currentUser.login(token);
//若没有指定账户,则shiro将会抛出异常。
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
//若密码错误,则shiro将会抛出异常。
} 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?
}
}
//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)
//测试用户是否具备某一个行为,调用Subject的isPermitted方法
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();