com.soento.shiro.support.AuthRealm Maven / Gradle / Ivy
package com.soento.shiro.support;
import com.soento.core.lang.UserInfo;
import com.soento.core.support.MessageSourceAccessor;
import com.soento.shiro.lang.JwtToken;
import com.soento.shiro.lang.UserData;
import com.soento.shiro.util.JwtUtil;
import com.soento.shiro.util.SecurityUtil;
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;
import javax.annotation.Resource;
/**
* @author yantao.zeng
*/
public class AuthRealm extends AuthorizingRealm {
/**
* 用户状态-锁定
*/
public static final String LOCK = "1";
@Resource
protected MessageSourceAccessor msa;
@Resource
protected AuthService authService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
UserInfo user = SecurityUtil.getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(user.getRoleIds());
info.setStringPermissions(user.getFunctionNames());
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
if (getAuthenticationTokenClass() == JwtToken.class) {
return getAuthInfoByToken(authcToken);
}
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
return getAuthInfo(token.getUsername(), new String(token.getPassword()));
}
protected AuthenticationInfo getAuthInfo(String username, String password) {
UserData user = authService.getUser(username);
if (null == user) {
throw new UnknownAccountException("用户不存在");
}
if (LOCK.equals(user.getStatus())) {
throw new DisabledAccountException("用户被锁定");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("账号或密码不正确");
}
UserInfo loginUser = user;
return new SimpleAuthenticationInfo(loginUser, user.getPassword(), getName());
}
private AuthenticationInfo getAuthInfoByToken(AuthenticationToken authcToken) {
JwtToken authc = (JwtToken) authcToken;
String token = (String) authc.getPrincipal();
UserInfo loginUser = JwtUtil.getLoginUser(token);
UserData user = authService.getUser(loginUser.getUsername());
if (null == user) {
throw new UnknownAccountException("用户不存在");
}
if (LOCK.equals(user.getStatus())) {
throw new DisabledAccountException("用户被锁定");
}
boolean result = false;
try {
result = JwtUtil.verify(token, loginUser, user.getPassword());
} catch (Exception e) {
throw new AuthenticationException(e);
}
if (!result) {
throw new IncorrectCredentialsException("用户名密码不正确");
}
return new SimpleAuthenticationInfo(loginUser, token, getName());
}
}