import org.apache.shiro.SecurityUtils;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.dao.User;
import com.example.demo.service.UserService;
/**
* @ClassName: MyRealm
* @Description: shiro 认证 + 授权 重写 */
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String account = (String)principals.getPrimaryPrincipal();
User user = new User();
user.setUsername(account);
String userId = user.getId();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
/**根据用户ID查询角色(role),放入到Authorization里.*/
info.setRoles(userService.findRoleByUserId(userId));
/**根据用户ID查询权限(permission),放入到Authorization里.*/
info.setStringPermissions(userService.findPermissionByUserId(userId));
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String phone = (String)token.getPrincipal(); //得到用户名
String password = new String((char[])token.getCredentials()); //得到密码
//根据用户名从数据库获取密码
// String pword = "123";
// if (phone == null) {
// try {
// throw new AccountException("用户名不正确");
// } catch (AccountException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// } else if (!password.equals(pword )) {
// try {
// throw new AccountException("密码不正确");
// } catch (AccountException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// return new SimpleAuthenticationInfo(phone, password,getName());
if(null != phone && null != password){
return new SimpleAuthenticationInfo(phone, password, getName());
}else{
return null;
}
}
/**
* 清空当前用户权限信息
*/
public void clearCachedAuthorizationInfo() {
PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
SimplePrincipalCollection principals = new SimplePrincipalCollection(
principalCollection, getName());
super.clearCachedAuthorizationInfo(principals);
}
/**
* 指定principalCollection 清除
*/
public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(
principalCollection, getName());
super.clearCachedAuthorizationInfo(principals);
}
}
shiro 认证 + 授权 重写
于 2019-11-06 18:12:21 首次发布