Shiro组件-Realm

Realm体系

在这里插入图片描述

  • 作用
      用以加载用户的角色与权限。底层实现类主要区别于数据获取方式的不同。
  • 源码
    • 顶级接口Realm:提供身份认证基本功能
    interface Realm{
    	String getName();//当前领域域的名称,每个领域对象名在同一应用中唯一
    	boolean supports(AuthenticationToken token);//返回当前领域是否支持参数token的类型,支持则可以调用getAuthenticationInfo(AuthenticationToken token)进行身份认证
    	AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;//返回参数token对应用户身份认证信息	
    }
    
    • 抽象类:CachingRealm增加缓存功能
    //	实现缓存功能
    abstract Class CachingRealm implements Realm,Nameable,CacheManagerAware,LogoutAware{
    	private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger();//实例的数
    	private String name;//唯一名字,通过实现Nameable中的String setName()生成
    	private CacheManager cacheManager;//通过实现CacheManagerAware的setCacheManager(),设置
    	private boolean cachingEnabled;//是否支持缓存
    	//设置名字为:类名+"_"+实例数目
    	public CachingRealm(){
    		this.cachingEnable = true;
    		this.name = getClass().getName()+"_"+INSTANCE_COUNT.getAndIncrement();	
    	}
    	//实现Nameable
    	public void setName(String name){
    		this.name = name;
    	}
    	//实现CacheManagerAware
    	public void setCacheManager(CacheManager cacheManager){
    		this.cacheManager = cacheManager;
    		afterCacheManagerSet();
    	}
    	//完成缓存管理器设置后的操作
    	public void afterCacheManagerSet(){}
    	public void setCachingEnabled(boolean cachingEnabled){
    		this.cachingEnabled = cachingEnabled;
    	}
    	//实现LogoutAware
    	public void onLogout(PrincipalCollection principals){
    		clearCache(principals);
    	}
    	//清空当前信息在cache的信息
    	public void clearCache(PrincipalCollection principals){
    		if(!CollectionUtils.isEmpty(principals)){
    			doClearCache(principals);
    			log.trace("Cleared cache entries for account with principals[{}],principals");
    		}
    	}
    	protected void doClearCache(PrincipalCollection principals) {}
    	public CacheManager getCacheManager(){
    		return this.cacheManager;
    	}
    	public String getName(){
    		return this.name;
    	}
    	public boolean isCachingEnabled(){
    		return this.cachingEnabled;
    	}
    	//获取可用的身份信息
    	protected Object getAvailablePrincipal(PrincipalCollection principals) {
        	Object primary = null;
        	if (!CollectionUtils.isEmpty(principals)) {
            	Collection thisPrincipals = principals.fromRealm(getName());
            	if (!CollectionUtils.isEmpty(thisPrincipals)) {
                	primary = thisPrincipals.iterator().next();
            	} else {
                	//no principals attributed to this particular realm.  Fall back to the 'master' primary:
                	primary = principals.getPrimaryPrincipal();
            	}
        	}
        return primary;
        }
    }
    
    • 抽象类:AuthenticatingRealm增加认证功能
     //省略属性的getter与setter
    abstract class AuthenticatingRealm extends CachingRealm implements Initializable{
    	private static final Logger = LoggerFactory.getLogger(AuthenticatingRealm.class);
    	private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger();
    	//认证器缓存后缀
    	private static final String DEFAULT_AUTHENTICATION_CACHE_SUFFIX = ".authenticationCache";
    	//加密密码和验证密码
    	private CredentialsMatcher credentialsMatcher;
        //支持的认证令牌类型
        private Class<? extends AuthenticationToken> authenticationTokenClass;
    	//用以缓存认证信息
    	private Cache<Object, AuthenticationInfo> authenticationCache;
    	private boolean authenticationCachingEnabled;
        private String authenticationCacheName;
    
    	//构造方法
    	public AuthenticatingRealm(){}
    	public AuthenticatingRealm(CacheManager cacheManager){}
    	//实质上都调用的是此构造函数
    	public AuthenticatingRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
    	    authenticationTokenClass = UsernamePasswordToken.class;
    		this.authenticationCachingEnabled = false; 
            int instanceNumber = INSTANCE_COUNT.getAndIncrement();
            this.authenticationCacheName = getClass().getName() + DEFAULT_AUTHENTICATION_CACHE_SUFFIX;
            if (instanceNumber > 0) {
                this.authenticationCacheName = this.authenticationCacheName + "." + instanceNumber;
            }
            if (cacheManager != null) {
            	setCacheManager(cacheManager);
            }
            if (matcher != null) {
              setCredentialsMatcher(matcher);
            }
        }
      	//认证功能
      	private Cache<Object,AuthenticainoInfo> getAuthenticationCacheLazy(){}
      	private AuthenticationInfo getCachedAuthenticationInfo(AuthenticationToken token){}
      	private void cacheAuthenticationInfoPossible(AuthenticationToken token,AuthenticationInfo info){}
      	public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {}
      	protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException{}
      	protected Object getAuthenticationCacheKey(AuthenticationToken token){}
      	protected Object getAuthenticationCacheKey(PrincipalCollection principals){}
      	private static boolean isEmpty(PrincipalCollection pc){}
      	protected void clearCachedAuthenticationInfo(PrincipalCollection principals){}
      	//重写方法
      	public boolean supports(AuthenticationToken token){}
      	public void setName(String name){}
      	protected void afterCacheManagerSet(){}
      	protected void doClearCache(PrincipalCollection principals){}
      	protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
      	//实现接口
      	public final void init(){
      		getAvailableAuthenticationCache();
      		onInit();	
      	}
      	//服务接口
      	protected void onInit(){}
    }
    
    • 抽象类:AuthorizingRealm增加授权功能
    //省略属性的getter与setter
    abstract class AuthorizingRealm extends AuthenticatingRealm implements Authorizer,Initializable,PermissionResolverAware,RolePermissionResolverAware{
    	private static final Logger log = LoggerFactory.getLogger(AuthorizingRealm.class);
    	private static final String DEFAULT_AUTHORIZATION_CACHE_SUFFIX = ".authorizationCache";
    	private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger();
    //认证缓存属性
    	private boolean authorizationCachingEnabled;
    	private Cache<Object, AuthorizationInfo> authorizationCache;
    	private String authorizationCacheName;
    //新增授权属性
    	private PermissionResolver permissionResolver;
    	private RolePermissionResolver permissionRoleResolver;
    	
    //授权方法
    	//得到权限	
    	protected Collection<Permission> getPermissions(AuthorizationInfo info){}
    	private Collection<Permission> resolvePermissions(Collection<String> stringPerms){}
    	private Collection<Permission> resolveRolePermissions(Collection<String> roleNames){}
    	//是否拥有权限,PrincipalCollection是身份集合
    	public boolean isPermitted(PrincipalCollection principals, String permission){}
    	public boolean isPermitted(PrincipalCollection principals, Permission permission){}
    	public boolean[] isPermitted(PrincipalCollection principals, List<Permission> permissions){}
    	protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info){}
    	public boolean isPermittedAll(PrincipalCollection subjectIdentifier, String... permissions){}
    	//实质调用此方法
    	protected boolean isPermitted(Permission permission, AuthorizationInfo info){
    		Collection<Permission> perms = getPermissions(info);
        	if (perms != null && !perms.isEmpty()) {
        		for (Permission perm : perms) {
           			if (perm.implies(permission)) {
                     	return true;
                 	}
             	}
         	}
            return false;
       	}
    	//验证是否有此权限,实质调用isPermitted()方法,无权限则抛出异常。
    	public void checkPermission(PrincipalCollection subjectIdentifier, String permission) throws AuthorizationException{}
    	public void checkPermission(PrincipalCollection principal, Permission permission) throws AuthorizationException{}
    	protected void checkPermission(Permission permission, AuthorizationInfo info){}
    	public void checkPermissions(PrincipalCollection subjectIdentifier, String... permissions) throws AuthorizationException{}
    	public void checkPermissions(PrincipalCollection principal, Collection<Permission> permissions) throws AuthorizationException{}
    	protected void checkPermissions(Collection<Permission> permissions, AuthorizationInfo info){}
    	//是否拥有此角色
    	public boolean hasRole(PrincipalCollection principal, String roleIdentifier){}
    	public boolean[] hasRoles(PrincipalCollection principal, List<String> roleIdentifiers){}
    	protected boolean[] hasRoles(List<String> roleIdentifiers, AuthorizationInfo info){}
    	public boolean hasAllRoles(PrincipalCollection principal, Collection<String> roleIdentifiers){}
    	private boolean hasAllRoles(Collection<String> roleIdentifiers, AuthorizationInfo info){}
    	//实质调用此方法
    	protected boolean hasRole(String roleIdentifier, AuthorizationInfo info){
    		return info != null && info.getRoles() != null && info.getRoles().contains(roleIdentifier);
    	}
    	//检查是否拥有此角色,实质调用hasRoles()等方法,不具有此角色则抛出异常。
    	public void checkRole(PrincipalCollection principal, String role) throws AuthorizationException{}
    	protected void checkRole(String role, AuthorizationInfo info){}
    	public void checkRoles(PrincipalCollection principal, Collection<String> roles) throws AuthorizationException{}
    	public void checkRoles(PrincipalCollection principal, String... roles) throws AuthorizationException{}
    	protected void checkRoles(Collection<String> roles, AuthorizationInfo info){}
    	//重写方法
    	public void setName(String name){}
    	protected void onInit(){}
    	afterCacheManagerSet(){}
    	private Cache<Object, AuthorizationInfo> getAuthorizationCacheLazy(){}
    	private Cache<Object, AuthorizationInfo> getAvailableAuthorizationCache(){}
    	protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals){}
    	protected Object getAuthorizationCacheKey(PrincipalCollection principals){}
    	protected void clearCachedAuthorizationInfo(PrincipalCollection principals){}
    	protected void doClearCache(PrincipalCollection principals){}
    	//实现接口
    	//服务接口
    }
    
    • 实现类:JdbcRleam,从数据源中获得权限信息
    public class JdbcRealm extends AuthorizingRealm{
    	protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";
    	protected static final String DEFAULT_SALTED_AUTHENTICATION_QUERY = "select password, password_salt from users where username = ?";
    	protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?";
    	protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?";
    	private static final Logger log = LoggerFactory.getLogger(JdbcRealm.class);
    	public enum SaltStyle {NO_SALT, CRYPT, COLUMN, EXTERNAL};
    	
    	protected DataSource dataSource;
    	protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;
    	protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY;
    	protected String permissionsQuery = DEFAULT_PERMISSIONS_QUERY;
    	protected boolean permissionsLookupEnabled = false;
    	protected SaltStyle saltStyle = SaltStyle.NO_SALT;
    	protected boolean saltIsBase64Encoded = true;
    
    //数据库中获取权限信息
    	
    //重写方法
    	//从从数据库中得到数据
    	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{}
    	private String[] getPasswordForUser(Connection conn, String username) throws SQLException{}
    	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){}
    	protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException{}
    	protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException{}
    }	
    
    • 实现类:IniRealm,从INI文件中获得权限信息
    public class IniRealm extends TextConfigurationRealm{
    	public static final String USERS_SECTION_NAME = "users";
    	public static final String ROLES_SECTION_NAME = "roles";
    	private static transient final Logger log = LoggerFactory.getLogger(IniRealm.class);
    	private String resourcePath;	
    	private Ini ini;
    
    	public IniRealm(){}
    	public IniRealm(Ini ini){}
    	public IniRealm(String resourcePath){}
    //INI文件获得权限
    	private void processDefinitions(Ini ini){}
    //重写方法
    	protected void onInit(){}
    //实现接口
    //辅助接口
    }	
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值