What
Apache Shiro旨在成为最全面的,但也是最容易使用的Java安全框架。
文档
没有比官网更好的了 https://shiro.apache.org/get-started.html
简要分析
四大基石: 认证,授权,会话管理,加密
了解术语
Authentication:认证
Authorization:授权(访问控制)
其他:https://shiro.apache.org/terminology.html
架构
Shiro的架构有三个主要概念:Subject,SecurityManager和Realms
其他:https://shiro.apache.org/architecture.html
快速启动
获取当前用户(这里叫主题subject,代之用户,程序,上下文等,不叫user主要是防止shiro不跟其他框架重名)
Subject currentUser = SecurityUtils.getSubject();
获得会话session
Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );
登陆认证
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?
}
获得当前用户主体
currentUser.getPrincipal()
//是否有权限
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.