Apache Shiro | Simple. Java. Security.
java语言编写
架构
shiro认证流程
使用
添加shiro依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
SimpleAccountRealm
SimpleAccountRealm只支持role的授权 hasRole、checkRole
授权是认证之后的操作
public void authen() {
//认证的发起者(subject), SecurityManager, Realm
//1. 准备Realm(基于内存存储用户信息)
SimpleAccountRealm realm = new SimpleAccountRealm();
realm.addAccount("admin", "admin", "超级管理员", "商家");
//2. 准备SecurityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//3. SecurityManager和Realm建立连接
securityManager.setRealm(realm);
//4. subject和SecurityManager建立联系
SecurityUtils.setSecurityManager(securityManager);
//5. 声明subject
Subject subject = SecurityUtils.getSubject();
//6. 发起认证
subject.login(new UsernamePasswordToken("admin", "admin"));
// 如果认证时,用户名错误,抛出:org.apache.shiro.authc.UnknownAccountException异常
// 如果认证时,密码错误,抛出:org.apache.shiro.authc.IncorrectCredentialsException:
//7. 判断是否认证成功
System.out.println(subject.isAuthenticated());
//8. 退出登录后再判断
// subject.logout();
// System.out.println("logout方法执行后,认证的状态:" + subject.isAuthenticated());
//9. 授权是在认证成功之后的操作!!!
// SimpleAccountRealm只支持角色的授权
System.out.println("是否拥有超级管理员角色:" + subject.hasRole("超级管理员"));
subject.checkRole("商家");
// check方法校验角色时,如果没有指定角色,会抛出异常:org.apache.shiro.authz.UnauthorizedException: Subject does not have role [角色信息]
}
IniRealm
基于文件存储用户名,密码,角色等信息
支持权限校验
public void authen(){
//1. 构建IniRealm
IniRealm realm = new IniRealm("classpath:shiro.ini");
//2. 构建SecurityManager绑定Realm
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setRealm(realm);
//3. 基于SecurityUtils绑定SecurityManager并声明subject
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
//4. 认证操作
subject.login(new UsernamePasswordToken("admin","admin"));
//5. 角色校验
// 超级管理员
System.out.println(subject.hasRole("超级管理员"));
subject.checkRole("运营");
//6. 权限校验
System.out.println(subject.isPermitted("user:update"));
// 如果没有响应的权限,就抛出异常:UnauthorizedException: Subject does not have permission [user:select]
subject.checkPermission("user:delete");
}
shiro.ini
[users]
username=password,role1,role2
admin=admin,超级管理员,运营
[roles]
role1=perm1,perm2
超级管理员=user:add,user:update,user:delete
JdbcRealm
通过数据库存储对应的用户、角色、权限信息
推荐使用经典五张表来存储
public void authen(){
//1. 构建JdbcRealm
JdbcRealm realm = new JdbcRealm();
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///shiro");
dataSource.setUsername("root");
dataSource.setPassword("root");
realm.setDataSource(dataSource);
// 开启权限校验
realm.setPer