当认证通过后,会自动进入授权流程,也就是进入授权的方法,doGetAuthorizationInfo().
继承AuthorizingRealm后,同时实现认证方法doGetAuthorizationInfo()、授权方法doGetAuthorizationInfo()方便
package com.atguigu.shiro.realms;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class MyShiro extends AuthorizingRealm{
//认证
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
return null;
}
//授权
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
// TODO Auto-generated method stub
return null;
}
}
认证所携带的用户信息就会传给授权方法,授权方法根据该用户信息查询数据库就能得到该用户的角色和权限并进行赋予
//授权 会被shiro回调的方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
System.out.println("doGetAuthorizationInfo.....");
//1. 从PrincipalCollection中获取登录用户的信息
Object principal = arg0.getPrimaryPrincipal();
//2. 利用登录用的信息获取用户的角色或权限(可能需要查询数据库)
Set<String> roles = new HashSet<>();
roles.add("user");
if("admin".equals(principal)){
roles.add("admin");
}
//3. 创建SimpleAuthorizationInfo对象并设置其roles属性
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
//4. 返回SimpleAuthorizationInfo
return simpleAuthorizationInfo;
}
当前登录的用户就携带了自身所对应的角色和权限了,授权完成。