package com.yuanchu.limslaboratory.shiro.realm; import com.yuanchu.limslaboratory.pojo.User; import com.yuanchu.limslaboratory.shiro.JwtToken; import com.yuanchu.limslaboratory.utils.RedisUtil; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class JwtRealm extends AuthorizingRealm { /** * 限定这个 Realm 只处理我们自定义的 JwtToken */ @Override public boolean supports(AuthenticationToken token) { return token instanceof JwtToken; } /** * 此处的 SimpleAuthenticationInfo 可返回任意值,密码校验时不会用到它 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { JwtToken jwtToken = (JwtToken) authcToken; if (jwtToken.getPrincipal() == null) { throw new AccountException("Token参数异常!"); } // 当前用户 String account = jwtToken.getPrincipal().toString(); // 当前用户的token String credentials = (String)jwtToken.getCredentials(); User user = (User) RedisUtil.get(credentials); // 用户不存在 if (user == null) { throw new UnknownAccountException("用户不存在!"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, account, getName()); return info; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); return info; } }