其他分享
首页 > 其他分享> > realm登录认证

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;
        }
    }

标签:info,permissionList,realm,iterator,登录,认证,roleList,employee,null
来源: https://blog.csdn.net/zhengchunyuaner/article/details/110672382