Shiro (一)Hello World
jar包
log4j-1.2.15.jar shiro-all-1.3.2.jar slf4j-api-1.6.1.jar slf4j-log4j12-1.6.1.jar
角色的配置在Shiro.ini 中
http://apache.fayea.com/shiro/1.3.2/shiro-root-1.3.2-source-release.zip
下载后的 shiro-root-1.3.2-source-release\shiro-root-1.3.2\samples\quickstart\src\main\resources中
hellow world说明
通过SecurityUtils获取当前用户
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
//测试Session,通过当前Subject实例getSession()
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
当前的用户是否被认证,即是否已登录
//调用Subject实例的isAuthenticated()认证
if (!currentUser.isAuthenticated()) {
//将用户名密码封装为UsernamePasswordToken
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//rememberMe
token.setRememberMe(true);
try {
//执行登录
currentUser.login(token);
}
//若没有指定用户则shiro会抛出UnknowAccountException异常
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
//若用户存在密码错误则抛出IncorrectCredentialsException
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 (AuthenticationException ae) {
//unexpected condition? error?
}
}
测试是否有该角色 test a role:
//利用hasRole方法查看当前用户是否有这个角色
if (currentUser.hasRole("schwartz")) {
log.info("----------->May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
测试用户是否具备 某个行为。挑用Subject的isPermitted方法
//当前角色可以对lightsaber做任何事儿
//# The 'schwartz' role can do anything (*) with
//any lightsaber:schwartz = lightsaber:* 来自shiro.ini
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:
//可以对winbago这个类型的eagle5实例干drive这件事儿
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!");
}
执行登出
currentUser.logout();