1. 介绍
Apache Shiro是一个功能强大且易于使用的Java安全框架,它为开发人员提供了一种直观,全面的身份验证,授权,加密和会话管理解决方案。实际上,它可以管理应用程序安全性的所有方面,同时尽可能避免干扰。它建立在可靠的界面驱动设计和OO原则的基础上,可在您可以想象的任何地方实现自定义行为。但是,只要对所有内容都使用合理的默认值,就可以像应用程序安全性一样“轻松”。可以做什么:身份验证,授权管理,缓存管理,会话管理,加密功能等都以做到。
2. 使用下载(或者Maven添加依赖)
下载: 解压源码包:
$ unzip shiro-root-1.5.3-source-release.zip
输入快速入门目录:
$cdshiro-root-1.5.3/samples/quickstart
运行快速入门:
$ mvn compileexec:java
添加依赖:(进入Meave查看)
3. 快速入门
获取当前用户:
Subject currentUser = SecurityUtils.getSubject();
使用SecurityUtils。getSubject(),我们可以获得当前正在执行的Subject。一个主题就是一个应用程序的用户的安全,具体的“视图”。我们实际上想将其称为“用户”,getSubject()独立应用程序中的调用可能会Subject在特定于应用程序的位置中返回基于用户数据的,而在服务器环境(例如Web应用程序)中,它会获取Subject与当前线程或传入请求相关联的基于用户数据的。
获取当前会话:
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
这Session是Shiro特有的实例,它提供了常规HttpSession所使用的大部分功能,但具有一些额外的优点和一个很大的不同:它不需要HTTP环境!如果部署在Web应用程序内部,则默认情况下Session将HttpSession基于该应用程序。但是,在非Web环境中,例如简单的快速入门,Shiro将默认自动使用其企业会话管理。这意味着无论部署环境如何,您都可以在任何层的应用程序中使用相同的API。
对用户进行登入检查示例:
if ( !currentUser.isAuthenticated() ) {
//collect user principals and credentials in a gui specific manner
//such as username/password html form, X509 certificate, OpenID, etc.
//We'll use the username/password example here since it is the most common.
//(do you know what movie this is from? ;)
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//this is all you have to do to support 'remember me' (no config - built in!): 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?
}
获取登入的用户信息:
//print their identifying principal (in this case, a username): log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
判断用户是否有某个角色:
if ( currentUser.hasRole( "schwartz" ) ) {
log.info("May the Schwartz be with you!" );
} else {
log.info( "Hello, mere mortal." );
}
判断用户是否有某种权限:
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.");
}
注销用户:
currentUser.logout(); //removes all identifying information and invalidates their session too.
网友评论