配置文件见上篇文章
角色和权限初步
shiro.ini文件
#配置用户
[users]
zhangsan=123456,role1
lisi=123456,role2
wangwu=123456,role3
zhaoliu=123456,role1,role2,role3
sunqi=123456,role4
#声明角色
[roles]
role1=user:query,user:add,user:update,user:delete,user:export
role2=user:query,user:add
role3=user:query,user:export
role4=*:*
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
/**
* @author w
* shiro的认证使用shiro.ini文件
*/
public class TestAuthenticationApp {
//日志输出工具
private static final transient Logger log = LoggerFactory.getLogger(TestAuthenticationApp.class);
public static void main(String[] args) {
String username="sunqi";
String password="123456";
log.info("My First Apache Shiro Application");
//1创建安全管理器的工厂对象 org.apache.shiro.mgt.SecurityManager;不能用java包里的
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
//2从使用工厂创建安全管理器
SecurityManager securityManager = factory.getInstance();
//3.把当前的安全管理器绑定到当前的线程
SecurityUtils.setSecurityManager(securityManager);
//4.使用SecurityUtils.getSubject得到主体对象
Subject subject = SecurityUtils.getSubject();
//5.封装用户名密码
AuthenticationToken token=new UsernamePasswordToken(username,password);
//6.得到认证
try {
subject.login(token);
System.out.println("认证完");
}/* catch (IncorrectCredentialsException e) {
System.out.println("密码不对");
}catch (UnknownAccountException e){
System.out.println("用户名不对");
}*/
//AuthenticationException是IncorrectCredentialsException和UnknownAccountException的父异常
catch (AuthenticationException e){
System.out.println("用户名或者密码不对");
}
//判断用户是否认证成功
boolean authenticated = subject.isAuthenticated();
System.out.println("是否认证通过"+authenticated);
// subject.logout();//退出的方法
//角色判断
boolean hasRole1 = subject.hasRole("role1");
System.out.println("是否有role1的角色"+hasRole1);
//分别判断集合里的角色 返回数组
List<String> roleId= Arrays.asList("role1","role2","role3");
boolean[] hasRoles = subject.hasRoles(roleId);
for (boolean hasRole : hasRoles) {
System.out.println("是否有"+hasRole);
}
//判断当前用户是否有roleId集合的所有角色
boolean hasAllRoles = subject.hasAllRoles(roleId);
System.out.println(hasAllRoles);
//权限判断
boolean permitted = subject.isPermitted("user:query");
System.out.println("判断当前用户是否有user:query的权限"+permitted);
boolean[] permitted1 = subject.isPermitted("user:query", "user:add", "user:update");
for (boolean b : permitted1) {
System.out.println(b);
}
boolean permittedAll = subject.isPermittedAll("user:query", "user:add", "user:update");
System.out.println(permittedAll);
}
}