package com.landtool.lanbase.common.shiro; import java.util.Set; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExpiredCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.landtool.lanbase.common.Constant; import com.landtool.lanbase.modules.org.entity.OrgUser; import com.landtool.lanbase.modules.org.service.OrgUserService; import com.landtool.lanbase.modules.sys.entity.SysUserToken; import com.landtool.lanbase.modules.sys.service.SysUserTokenService; /** * @author lanbase * @Description: TODO(认证) * @date 2017-6-23 15:07 */ @Component public class ShiroRealm extends AuthorizingRealm { @Autowired private OrgUserService orgUserService; @Autowired private SysUserTokenService sysUserTokenService; @Override public boolean supports(AuthenticationToken token) { return token instanceof ShiroToken; } /** * 授权 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { OrgUser user = (OrgUser)principals.getPrimaryPrincipal(); Long userId = user.getUserid(); //用户权限列表 Set permsSet = orgUserService.getUserPermissions(userId); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setStringPermissions(permsSet); return info; } /** * 认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { ShiroToken accessToken = (ShiroToken) token; OrgUser user; if (!accessToken.IsCasToken()) { // 根据accessToken,查询用户信息 SysUserToken tokenEntity = sysUserTokenService.queryByToken(accessToken.getPrincipal()); // token失效 if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) { throw new ExpiredCredentialsException("token失效,请重新登录"); } user = orgUserService.queryObject(tokenEntity.getUserId()); } else { //用户信息 user = orgUserService.queryByUserName(accessToken.getPrincipal()); } //账号锁定 if(Constant.UserStatus.DISABLE.getValue()==user.getUserstatus()){ throw new LockedAccountException("账号已被锁定,请联系管理员"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token.getPrincipal(), getName()); return info; } }