package com.whyc.realm; import com.whyc.anotation.Realm; import com.whyc.constant.SuperConstant; import com.whyc.pojo.User; import com.whyc.service.UserBridgeService; import org.apache.shiro.authc.*; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import javax.annotation.PostConstruct; /** * 实际处理认证授权,跟数据库交互 */ @Realm public class CustomRealm extends AuthorizingRealm { /**必须@Lazy注解,@Lazy与@Autowired组合,使得依赖于Service相关的Bean都是lazy-resolution proxy*/ @Lazy @Autowired UserBridgeService userBridgeService; /** * 认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String userName = (String) authenticationToken.getPrincipal(); User user = userBridgeService.findPasswordAndSlatByUserName(userName); if(user.getId()==0){ System.out.printf("账号不存在"); throw new UnknownAccountException("账号不存在"); } return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName()); } /** * 授权 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { User user = (User) principalCollection.getPrimaryPrincipal(); return userBridgeService.getAuthorizationInfo(user); } /**加密*/ @PostConstruct public void initCredentialsMatcher() { HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(SuperConstant.HASH_ALGORITHM); matcher.setHashIterations(SuperConstant.HASH_INTERATIONS); setCredentialsMatcher(matcher); } }