确保JDK 1.6+,Maven 3.0.3+,此处使用1.3.2版本的源码版本
$ unzip shiro-root-1.3.2-source-release.zip
进入quickstart目录,并执行编译
$ cd shiro-root-1.3.2/samples/quickstart
$ mvn compile exec:java
Quickstart.java
Quickstart.java
包含所有需要熟悉的代码,下面条分缕析整个代码流程。
首先,是获取正在操作的用户
Subject currentUser = SecurityUtils.getSubject();
如果希望在会话过程中,让用户可以获取某些信息,可以操作会话
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
默认,shiro在web应用中集成,则Session与HttpSession相关。在非web应用中,Session则与HttpSession无关。
验证Subject登录
if ( !currentUser.isAuthenticated() ) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
currentUser.login(token);
}
如果登录失败,可以对各种异常进行处理
try {
currentUser.login( token );
//if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
//password didn't match, try again?
} catch ( LockedAccountException lae ) {
//account for that username is locked - can't login. Show them a message?
}
... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
//unexpected condition - error?
}
可以对登录信息等进行日志记录
log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
验证Subject是否拥有某个角色
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
查看Subject是否有某项权限
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.");
}
甚至可以查看subject是否对某项实例存在权限
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();