1,授权流程

自定义Realm实现授权_System

2,为使用要使用自定义Realm实现授权

与上边认证自定义realm一样,大部分情况是要从数据库获取权限数据,这里直接实现基于资源的授权。

3,UserRealm实现代码

public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return "UserRealm";
}
//用于认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
//从token中获取身份信息
String username = (String)token.getPrincipal();
//根据用户名到数据库中取出用户信息 如果查询不到 返回null
String password = "1111";//假如从数据库中获取密码为1111
//返回认证信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());
return simpleAuthenticationInfo;
}
//用于授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
//获取身份信息
String username = (String)principals.getPrimaryPrincipal();
//根据身份信息获取权限数据
//模拟
List<String">> permissions = new ArrayList<String">>();
permissions.add("user:save");
permissions.add("user:delete");
//将权限信息保存到AuthorizationInfo中
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for(String permission:permissions){
simpleAuthorizationInfo.addStringPermission(permission);
}
return simpleAuthorizationInfo;
}
}

4,配置文件 shiro.ini

[main]
#自定义 realm
userRealm=cn.siggy.realm.UserRealm
#将realm设置到securityManager
securityManager.realms=$userRealm

5, 测试代码

public static void main(String[] args) {
// 1.创建securityManager工厂 ecurityManager JDK也有这个类,在java.lang包 注意不要使用jdk里面那个类
Factory<SecurityManager">> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.创建securityManager
SecurityManager securityManager = factory.getInstance();
// 3.将securityManager绑定到运行环境
SecurityUtils.setSecurityManager(securityManager);
// 4.创建主体 只要线程不变,Subject不变
Subject subject = SecurityUtils.getSubject();
// 5.创建token用于认证 客户端传递过来的用户名和密码
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "zs");
// 6.登录(认证)
try {
subject.login(token);
System.out.println("登录成功");
} catch (IncorrectCredentialsException e) {
System.out.println("密码不正确");
}catch (UnknownAccountException e) {
System.out.println("没有这个帐号");
}catch (AuthenticationException e) {
e.printStackTrace();
}
System.out.println("认证状态:" + subject.isAuthenticated());
// 7.授权 基于角色授权 基于资源的授权
// 7.1基于角色授权
// 授权单个
boolean permitted = subject.hasRole("role1");
System.out.println("这是授权单个:" + permitted);

boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1", "role2", "role3"));
System.out.println("这是多个授权:" + hasAllRoles);

// 使用check方法进行授权,如果授权不通过会抛出异常
// subject.checkRole("role13");

// 7.2 基于资源的授权
// isPermitted传入权限标识符
boolean isPermitted = subject.isPermitted("user:create:1");
System.out.println("单个权限判断" + isPermitted);

boolean isPermittedAll = subject.isPermittedAll("user:create:1", "user:delete");
System.out.println("多个权限判断" + isPermittedAll);

// 使用check方法进行授权,如果授权不通过会抛出异常
try {
subject.checkPermission("items:create:1");
} catch (UnauthorizedException e) {
// e.printStackTrace();
System.out.println("没有这个权限");
}
}