realm登录认证

CrmRealm

@Component
public class CrmRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Employee employee = (Employee)principals.getPrimaryPrincipal();
        if (employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }else {
            //获取当前用户的所有角色
           List<Role> roleList = roleMapper.selectByEmployeeId(employee.getId());
            //获取当前用户的所有权限
            List<String> permissionList = permissionMapper.selectExpressionByCurrentuserId(employee.getId());
            //roleList.iterator().hasNext() && roleList.iterator().next()==null
           if (roleList.iterator().hasNext() &&roleList.iterator().next()==null|| permissionList.iterator().hasNext()&&permissionList.iterator().next()==null){
               info.addRoles(new ArrayList<String>());
               info.addStringPermissions(new ArrayList<String>());
               return info;
           }
           List<String> roleSnList = new ArrayList<>();
           for (Role role : roleList) {
                roleSnList.add(role.getSn());
            }
            if(roleSnList.size()>0)
            info.addRoles(roleSnList);

            if(permissionList!=null && permissionList.size()>0)
            info.addStringPermissions(permissionList);
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        String currentusername = (String) token.getPrincipal();
        Employee employee = employeeMapper.selectByName(currentusername);
        if (employee != null){
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(currentusername) ,this.getName());
            return simpleAuthenticationInfo;
        }else {
            return null;
        }
    }
上一篇:走进shiro,构建安全的应用程序---shiro修仙序章


下一篇:【免费下载】全套最新 018-1权限管理框架Shiro 视频教程+教学资料+学习课件+源代码+软件开发工具