package com.github.ouyangbob.admin.account.shiro; import javax.annotation.PostConstruct; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.crypto.hash.Md5Hash; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.ouyangbob.admin.account.model.entity.AdminUser; import com.github.ouyangbob.admin.account.service.IAdminUserService; import com.github.ouyangbob.shiro.ShiroUser; @SuppressWarnings("restriction") @Service public class ShiroSpringRealm extends AuthorizingRealm { private static final Logger logger=LoggerFactory.getLogger(ShiroSpringRealm.class); @Autowired protected IAdminUserService adminUserService; /** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; AdminUser adminUser=adminUserService.findAdminUserByLoginName(token.getUsername()); if (adminUser != null) { SimpleAuthenticationInfo info = new SimpleAuthenticationInfo( new ShiroUser(adminUser.getId(), adminUser.getLoginName()) , adminUser.getLoginPasswd() , getName()); return info; } else { throw new UnknownAccountException(token.getUsername()); } } /** * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { logger.error("doGetAuthorizationInfo:{}",principals); //AdminUser adminUser = (AdminUser) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addRole("admin"); info.addStringPermission("/admin/*"); return info; } /** * 设定Password校验的Hash算法与迭代次数. */ @PostConstruct public void initCredentialsMatcher() { HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Md5Hash.ALGORITHM_NAME); matcher.setHashIterations(2); setCredentialsMatcher(matcher); } }