阅读源码有助于陶冶情操,本文旨在简单的分析shiro在Spring中的使用html
Shiro是一个强大易用的Java安全框架,提供了认证、受权、加密和会话管理等功能java
Realm->CachingRealm->AuthenticatingRealm->AuthorizingRealm
本文只针对以上关系进行讲解,其他的实现类请自行查看源码web
Realm提供了安全的访问应用的相关实体类,好比用户、角色、权限,对其中的访问应用相应的认证或者受权操做。其提供的主要的方法为AuthenticationInfo#getAuthenticationInfo
,涉及的内容是关于信息的认证,这主要由AuthencatingRealm
类实现算法
提供缓存功能,简单看下其下的变量以及主要方法。spring
//设置是否容许缓存,构造函数中默认为true private boolean cachingEnabled; //设置缓存管理器,须要另外引入 private CacheManager cacheManager;
//获取principal对象,通常都是子类在执行受权操做赋予的 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; }
简单分析下其主要私有变量以及方法apache
//与父类的cachingEnabled结合使用,在构造函数里其默认是false private boolean authenticationCachingEnabled; //用户凭证验证类,好比校验密码是否一致 private CredentialsMatcher credentialsMatcher; //认证Token类,默认为UsernamePasswordToken类 private Class<? extends AuthenticationToken> authenticationTokenClass;
//可见若是只设置authenticationCachingEnable,其为true,也会设置cachingEnable=true public void setAuthenticationCachingEnabled(boolean authenticationCachingEnabled) { this.authenticationCachingEnabled = authenticationCachingEnabled; if (authenticationCachingEnabled) { setCachingEnabled(true); } }
//可见是否应用缓存是根据authenticationCachingEnabled和cachingEnabled联合判断的 public boolean isAuthenticationCachingEnabled() { return this.authenticationCachingEnabled && isCachingEnabled(); }
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //获取缓存中的认证信息,其中也会涉及到调用isAuthenticationCachingEnabled AuthenticationInfo info = getCachedAuthenticationInfo(token); if (info == null) { //otherwise not cached, perform the lookup: //调用doGetAuthenticationInfo方法,此处为抽象类,供子类调用 info = doGetAuthenticationInfo(token); log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info); if (token != null && info != null) { cacheAuthenticationInfoIfPossible(token, info); } } else { log.debug("Using cached authentication info [{}] to perform credentials matching.", info); } if (info != null) { //对获取的认证信息进行校验,通常是比对凭证加密后是否还一致 assertCredentialsMatch(token, info); } else { log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token); } return info; }
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException ;
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException { //获取私有属性credentialsMatcher CredentialsMatcher cm = getCredentialsMatcher(); if (cm != null) { //校验方法 if (!cm.doCredentialsMatch(token, info)) { //not successful - throw an exception to indicate this: String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials."; throw new IncorrectCredentialsException(msg); } } else { //可见credentialsMatcher属性必需要设定,不然会抛异常 throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " + "credentials during authentication. If you do not wish for credentials to be examined, you " + "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance."); } }
其中的内容和其父类验证抽象类基本类似,这里就不赘述了,主要提下主要方法api
//受权 protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) { if (principals == null) { return null; } AuthorizationInfo info = null; if (log.isTraceEnabled()) { log.trace("Retrieving AuthorizationInfo for principals [" + principals + "]"); } //是否引用cache Cache<Object, AuthorizationInfo> cache = getAvailableAuthorizationCache(); if (cache != null) { if (log.isTraceEnabled()) { log.trace("Attempting to retrieve the AuthorizationInfo from cache."); } Object key = getAuthorizationCacheKey(principals); info = cache.get(key); if (log.isTraceEnabled()) { if (info == null) { log.trace("No AuthorizationInfo found in cache for principals [" + principals + "]"); } else { log.trace("AuthorizationInfo found in cache for principals [" + principals + "]"); } } } if (info == null) { // Call template method if the info was not found in a cache //调用受权抽象方法,供子类实现 info = doGetAuthorizationInfo(principals); // If the info is not null and the cache has been created, then cache the authorization info. if (info != null && cache != null) { if (log.isTraceEnabled()) { log.trace("Caching authorization info for principals: [" + principals + "]."); } Object key = getAuthorizationCacheKey(principals); cache.put(key, info); } } return info; }
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
下述示例结合了受权与验证,即继承AuthorizingRealm便可浏览器
<!--缓存管理器--> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean> <!-- 凭证匹配器 --> <bean id="credentialsMatcher" class="com.jing.test.cas.admin.core.shiro.RetryLimitHashedCredentialsMatcher"> <constructor-arg ref="cacheManager"/> <property name="hashAlgorithmName" value="md5"/> <property name="hashIterations" value="2"/> <property name="storedCredentialsHexEncoded" value="true"/> </bean> <!--密码处理类--> <bean id="passwordService" class="com.jing.test.cas.admin.core.shiro.ShiroPasswordService"></bean> <!-- Realm实现 --> <bean id="shiroDBRealm" class="com.jing.test.cas.admin.core.shiro.ShiroDBRealm"> <property name="credentialsMatcher" ref="credentialsMatcher"/> <property name="cachingEnabled" value="false"/> <property name="shiroPasswordService" ref="passwordService"/> <property name="shiroUserService" ref="shiroUserService"/> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroDBRealm"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!-- 至关于调用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean> <!-- Shiro的Web过滤器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login"/> <property name="successUrl" value="/index.html"/> <property name="unauthorizedUrl" value="/403.html"/> <property name="filters"> <util:map> <entry key="authc" value-ref="formAuthenticationFilter"/> <entry key="perm" value-ref="permissionsAuthorizationFilter"/> <entry key="captcha" value-ref="captchaValidateFilter"/> <entry key="sysUser" value-ref="sysUserFilter"/> <entry key="user" value-ref="userFilter"/> </util:map> </property> <property name="filterChainDefinitions"> <!-- 若是不该用acm cas方案则添加 /logout=logout --> <value> /ossmanager/api/** = anon /test/** = anon /login = captcha,authc /logout=logout /index = anon /jcaptcha.jpeg = anon /403.html = anon /login.html = anon /favicon.ico = anon /static/** = anon /index.html=user,sysUser /welcome.html=user,sysUser /admin/user/modifyPwd.html=user,sysUser /admin/user/updatePassword=user,sysUser /admin/user/role/list=user,sysUser /** = user,sysUser,perm </value> </property> </bean> <!-- Shiro生命周期处理器--> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
package com.jing.test.cas.admin.core.shiro; import com.jing.test.cas.admin.core.exceptions.BizException; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Set; /** *Realm接口实现类 */ public class ShiroDBRealm extends AuthorizingRealm { /** * 日志对象 */ private static final Logger logger = LoggerFactory.getLogger(ShiroDBRealm.class); /** * 帐户禁用 */ private static final String USER_STATUS_FORBIDDEN = "1"; /** * 权限相关用户服务接口 */ private IShiroUserService shiroUserService; /** * 密码服务类 加密做用 */ private ShiroPasswordService shiroPasswordService; /** * 受权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 由于非正常退出,即没有显式调用 SecurityUtils.getSubject().logout() // (多是关闭浏览器,或超时),但此时缓存依旧存在(principals),因此会本身跑到受权方法里。 if (!SecurityUtils.getSubject().isAuthenticated()) { doClearCache(principalCollection); SecurityUtils.getSubject().logout(); return null; } ShiroUser shiroUser = (ShiroUser)principalCollection.getPrimaryPrincipal(); String userName = shiroUser.getUserName(); if(StringUtils.isNotBlank(userName)){ SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo(); try { Set<String> roleIds= shiroUserService.getRoles(userName); for (String roleId: roleIds){ shiroUser.setRoleId(roleId); } sazi.addRoles(roleIds); sazi.addStringPermissions(shiroUserService.getPermissions(userName)); return sazi; } catch (Exception e) { logger.error(e.getMessage(),e); } } return null; } /** * 认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; ShiroUser shiroUser = shiroUserService.getShiroUser(token.getUsername()); checkUserStatus(shiroUser); if(shiroUser != null){ SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(shiroUser,shiroUser.getPassword(),ByteSource.Util.bytes(shiroUser.getUserName()+shiroPasswordService.getPublicSalt()),getName()); return authenticationInfo; } return null; } /** * 检查用户状态 * @param shiroUser */ private void checkUserStatus(ShiroUser shiroUser) { if(StringUtils.equalsIgnoreCase(shiroUser.getUserStatus(),USER_STATUS_FORBIDDEN)){ throw new ForbiddenException("用户已被禁用"); } } /** * 初始化方法 * 设定Password校验的Hash算法与迭代次数. **/ public void initCredentialsMatcher() { HashedCredentialsMatcher matcher = new HashedCredentialsMatcher( shiroPasswordService.getHashAlgorithm()); matcher.setHashIterations(shiroPasswordService.getHashInterations()); setCredentialsMatcher(matcher); } public void setShiroUserService(IShiroUserService shiroUserService) { this.shiroUserService = shiroUserService; } public void setShiroPasswordService(ShiroPasswordService shiroPasswordService) { this.shiroPasswordService = shiroPasswordService; } }
受权与验证的逻辑作了简单的了解,其中受权可经过subject.isPermited()等方法调用;验证则可经过subject.login()等方法来调用缓存