Shiro
一、Shiro的简介
1、简介
Shiro 是一个Java的安全(权限)框架。
可以完成认证,授权,加密,缓存等功能
2、功能
-
Authentication:身份认证、登录。验证用户是否有相应的身份
-
Authorization:授权。判断用户是否有某个权限
-
Session Manager: 会话管理
-
Crytography:加密。加密存储到数据库
-
Caching: 缓存。用户登录信息等
二、Shiro快速开始
1、 使用DefaultSecurityManager( ) 读取ini配置
2、 getSubject( ) 获取当前用户,**getSession( )**获取Session
3、 **setAttribute( )**存值,取值
4、isAuthenticated( ) 判断当前用户是否被认证
5、hasRole( )
6、isPermitted( ) 粗粒度、细粒度
public static void main(String[] args) {
// (1) 读取ini配置文件
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
IniRealm iniRealm= new IniRealm("classpath:shiro.ini");
defaultSecurityManager.setRealm(iniRealm);
SecurityUtils.setSecurityManager(defaultSecurityManager);
// (2) 获得当前用户
Subject currentUser = SecurityUtils.getSubject();
// 获得当前用户的session
Session session = currentUser.getSession();
//(3) 存值,取值
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// (4) 判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
// token令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
// 设置记住我
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} 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?
}
}
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//粗粒度
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//细粒度
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();
System.exit(0);
}