package com.lf.server.entity.sys; import com.lf.server.service.sys.UserService; import org.apache.shiro.SecurityUtils; 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 org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; /** * MyRealm * @author */ public class MyRealm extends AuthorizingRealm { @Autowired UserService userService; /** * 执行授权 * * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { // 认证之后,如果前端shiro标签中有出现需要权限的标签,或者过滤器中某个链接需要权限,就会进行认证 System.out.println("执行了授权"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // 获得当前subject Subject subject = SecurityUtils.getSubject(); // 获得当前的principal,也就是认证完后我们放入的信息 User currentUser = (User) subject.getPrincipal(); // 添加权限 info.addStringPermission(currentUser.getPerms()); // 添加角色 info.addRole(currentUser.getRole()); return info; } /** * 执行认证 * * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行了认证"); UsernamePasswordToken userToken = (UsernamePasswordToken) token; // 从数据库中查询该用户 User user = userService.queryUserByName(userToken.getUsername()); // 如果不存在该用户,返回一个空错误,前端也可以相应显示提示 if (user == null) { return null; } // 第一个参数为principal;第二个参数为从数据库中查出的用于验证的密码,shiro中密码验证不需要我们自己去做;第三个参数为realmName return new SimpleAuthenticationInfo(user, user.getPassword(), getName()); } }