flowable工作流引擎如何实现自定义权限管理

小编给大家分享一下flowable工作流引擎如何实现自定义权限管理,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

场景:  对已有系统集成工作流,系统已经有一整套的权限管理模块,并且后期需要改造为单独的微服务,无法简单通过网上的建立视图进行解决,同时考虑到数据同步到 flowable 的方式,需要改造现有系统的代码,后期如果接入无人维护的系统,比较麻烦。如果选择自定义查询,可以更灵活定制。虽然会有一定的开发工作量,但比较符合目前的系统现状。

想法:参考 集成 LDAP 的实现方式  

可以覆盖IdmIdentityServiceImpl类,或者直接实现IdmIdentityService接口,并使用实现类作为ProcessEngineConfiguration中的idmIdentityService参数。

参考 LDAPIdentityServiceImpl  的注册到 flowable 引擎配置类的实现方式

flowable工作流引擎如何实现自定义权限管理

在SpringBoot中,可以向ProcessEngineConfigurationbean定义添加下面的代码实现:

@Bean
    public EngineConfigurationConfigurer<SpringIdmEngineConfiguration> MyIdmEngineConfigurer() {
        return idmEngineConfiguration -> idmEngineConfiguration
                .setIdmIdentityService(new IdmIdentityServiceHandler());
    }

其中 IdmIdentityServiceHandler  同样参考 LDAPIdentityServiceImpl  继承 IdmIdentityServiceImpl 进行处理。

package com.jxlgzwh.handler;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.idm.api.*;
import org.flowable.idm.engine.impl.IdmIdentityServiceImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class IdmIdentityServiceHandler extends IdmIdentityServiceImpl {


    private static final Logger LOGGER = LoggerFactory.getLogger(IdmIdentityServiceHandler.class);


    @Override
    public UserQuery createUserQuery() {
        System.out.println("用户查询--");
        return null;
    }

    @Override
    public GroupQuery createGroupQuery() {
        System.out.println("用户组查询--");
        return null;
    }

    @Override
    public boolean checkPassword(String userId, String password) {
        return true;
    }

    @Override
    public List<Group> getGroupsWithPrivilege(String name) {
        System.out.println("查询--");
        throw new FlowableException("LDAP identity service doesn't support creating a new user");
    }

    @Override
    public List<User> getUsersWithPrivilege(String name) {
        System.out.println("查询--");
        throw new FlowableException("LDAP identity service doesn't support creating a new user");
    }

    @Override
    public User newUser(String userId) {
        throw new FlowableException("LDAP identity service doesn't support creating a new user");
    }

    @Override
    public void saveUser(User user) {
        throw new FlowableException("LDAP identity service doesn't support saving an user");
    }

    @Override
    public NativeUserQuery createNativeUserQuery() {
        throw new FlowableException("LDAP identity service doesn't support native querying");
    }

    @Override
    public void deleteUser(String userId) {
        throw new FlowableException("LDAP identity service doesn't support deleting an user");
    }

    @Override
    public Group newGroup(String groupId) {
        throw new FlowableException("LDAP identity service doesn't support creating a new group");
    }

    @Override
    public NativeGroupQuery createNativeGroupQuery() {
        throw new FlowableException("LDAP identity service doesn't support native querying");
    }

    @Override
    public void saveGroup(Group group) {
        throw new FlowableException("LDAP identity service doesn't support saving a group");
    }

    @Override
    public void deleteGroup(String groupId) {
        throw new FlowableException("LDAP identity service doesn't support deleting a group");
    }
}

考虑到不需要对 flowable 的 权限进行维护,所以无需实现 新增 和修改方法。

验证: 写个方法进行测试是否生效

    @RequestMapping(value = "is")
    @ResponseBody
    public String identityService() {

        identityService.createUserQuery();

        return "测试";
    }

flowable工作流引擎如何实现自定义权限管理

访问方法,后台打印  “用户查询--“  表明配置成功。

集成 LDAP 的完整代码 可以在GitHub查看代码:LDAPIdentityServiceImpl。

其中 用户查询   LDAPUserQueryImpl   继承了   UserQueryImpl   ; 用户组查询  LDAPGroupQueryImpl extends GroupQueryImpl  

/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.ldap.impl;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.User;
import org.flowable.idm.engine.impl.UserQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.flowable.ldap.LDAPCallBack;
import org.flowable.ldap.LDAPConfiguration;
import org.flowable.ldap.LDAPTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LDAPUserQueryImpl extends UserQueryImpl {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = LoggerFactory.getLogger(LDAPUserQueryImpl.class);

    protected LDAPConfiguration ldapConfigurator;

    public LDAPUserQueryImpl(LDAPConfiguration ldapConfigurator) {
        this.ldapConfigurator = ldapConfigurator;
    }

    @Override
    public long executeCount(CommandContext commandContext) {
        return executeQuery().size();
    }

    @Override
    public List<User> executeList(CommandContext commandContext) {
        return executeQuery();
    }

    protected List<User> executeQuery() {
        if (getId() != null) {
            List<User> result = new ArrayList<>();
            result.add(findById(getId()));
            return result;

        } else if (getIdIgnoreCase() != null) {
            List<User> result = new ArrayList<>();
            result.add(findById(getIdIgnoreCase()));
            return result;

        } else if (getFullNameLike() != null) {
            return executeNameQuery(getFullNameLike());

        } else if (getFullNameLikeIgnoreCase() != null) {
            return executeNameQuery(getFullNameLikeIgnoreCase());

        } else {
            return executeAllUserQuery();
        }
    }

    protected List<User> executeNameQuery(String name) {
        String fullName = name.replaceAll("%", "");
        String searchExpression = ldapConfigurator.getLdapQueryBuilder().buildQueryByFullNameLike(ldapConfigurator, fullName);
        return executeUsersQuery(searchExpression);
    }

    protected List<User> executeAllUserQuery() {
        String searchExpression = ldapConfigurator.getQueryAllUsers();
        return executeUsersQuery(searchExpression);
    }

    protected UserEntity findById(final String userId) {
        LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
        return ldapTemplate.execute(new LDAPCallBack<UserEntity>() {

            @Override
            public UserEntity executeInContext(InitialDirContext initialDirContext) {
                try {

                    String searchExpression = ldapConfigurator.getLdapQueryBuilder().buildQueryByUserId(ldapConfigurator, userId);

                    String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
                    NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());
                    UserEntity user = new UserEntityImpl();
                    while (namingEnum.hasMore()) { // Should be only one
                        SearchResult result = (SearchResult) namingEnum.next();
                        mapSearchResultToUser(result, user);
                    }
                    namingEnum.close();

                    return user;

                } catch (NamingException ne) {
                    LOGGER.error("Could not find user {} : {}", userId, ne.getMessage(), ne);
                    return null;
                }
            }

        });
    }

    protected List<User> executeUsersQuery(final String searchExpression) {
        LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
        return ldapTemplate.execute(new LDAPCallBack<List<User>>() {

            @Override
            public List<User> executeInContext(InitialDirContext initialDirContext) {
                List<User> result = new ArrayList<>();
                try {
                    String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
                    NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());

                    while (namingEnum.hasMore()) {
                        SearchResult searchResult = (SearchResult) namingEnum.next();

                        UserEntity user = new UserEntityImpl();
                        mapSearchResultToUser(searchResult, user);
                        result.add(user);

                    }
                    namingEnum.close();

                } catch (NamingException ne) {
                    LOGGER.debug("Could not execute LDAP query: {}", ne.getMessage(), ne);
                    return null;
                }
                return result;
            }

        });
    }

    protected void mapSearchResultToUser(SearchResult result, UserEntity user) throws NamingException {
        if (ldapConfigurator.getUserIdAttribute() != null) {
            user.setId(result.getAttributes().get(ldapConfigurator.getUserIdAttribute()).get().toString());
        }
        if (ldapConfigurator.getUserFirstNameAttribute() != null) {
            try {
                user.setFirstName(result.getAttributes().get(ldapConfigurator.getUserFirstNameAttribute()).get().toString());
            } catch (NullPointerException e) {
                user.setFirstName("");
            }
        }
        if (ldapConfigurator.getUserLastNameAttribute() != null) {
            try {
                user.setLastName(result.getAttributes().get(ldapConfigurator.getUserLastNameAttribute()).get().toString());
            } catch (NullPointerException e) {
                user.setLastName("");
            }
        }
        if (ldapConfigurator.getUserEmailAttribute() != null) {
            try {
                user.setEmail(result.getAttributes().get(ldapConfigurator.getUserEmailAttribute()).get().toString());
            } catch (NullPointerException e) {
                user.setEmail("");
            }
        }
    }

    protected SearchControls createSearchControls() {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
        return searchControls;
    }
}
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.ldap.impl;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.Group;
import org.flowable.idm.engine.impl.GroupQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntity;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.ldap.LDAPCallBack;
import org.flowable.ldap.LDAPConfiguration;
import org.flowable.ldap.LDAPGroupCache;
import org.flowable.ldap.LDAPTemplate;

public class LDAPGroupQueryImpl extends GroupQueryImpl {

    private static final long serialVersionUID = 1L;

    protected LDAPConfiguration ldapConfigurator;
    protected LDAPGroupCache ldapGroupCache;

    public LDAPGroupQueryImpl(LDAPConfiguration ldapConfigurator, LDAPGroupCache ldapGroupCache) {
        this.ldapConfigurator = ldapConfigurator;
        this.ldapGroupCache = ldapGroupCache;
    }

    @Override
    public long executeCount(CommandContext commandContext) {
        return executeQuery().size();
    }

    @Override
    public List<Group> executeList(CommandContext commandContext) {
        return executeQuery();
    }

    protected List<Group> executeQuery() {
        if (getUserId() != null) {
            return findGroupsByUser(getUserId());
        } else if (getId() != null) {
            return findGroupsById(getId());
        } else {
            return findAllGroups();
        }
    }

    protected List<Group> findGroupsByUser(String userId) {

        // First try the cache (if one is defined)
        if (ldapGroupCache != null) {
            List<Group> groups = ldapGroupCache.get(userId);
            if (groups != null) {
                return groups;
            }
        }

        String searchExpression = ldapConfigurator.getLdapQueryBuilder().buildQueryGroupsForUser(ldapConfigurator, userId);
        List<Group> groups = executeGroupQuery(searchExpression);

        // Cache results for later
        if (ldapGroupCache != null) {
            ldapGroupCache.add(userId, groups);
        }

        return groups;
    }

    protected List<Group> findGroupsById(String id) {
        String searchExpression = ldapConfigurator.getLdapQueryBuilder().buildQueryGroupsById(ldapConfigurator, id);
        return executeGroupQuery(searchExpression);
    }

    protected List<Group> findAllGroups() {
        String searchExpression = ldapConfigurator.getQueryAllGroups();
        List<Group> groups = executeGroupQuery(searchExpression);
        return groups;
    }

    protected List<Group> executeGroupQuery(final String searchExpression) {
        LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
        return ldapTemplate.execute(new LDAPCallBack<List<Group>>() {

            @Override
            public List<Group> executeInContext(InitialDirContext initialDirContext) {

                List<Group> groups = new ArrayList<>();
                try {
                    String baseDn = ldapConfigurator.getGroupBaseDn() != null ? ldapConfigurator.getGroupBaseDn() : ldapConfigurator.getBaseDn();
                    NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());
                    while (namingEnum.hasMore()) { // Should be only one
                        SearchResult result = (SearchResult) namingEnum.next();

                        GroupEntity group = new GroupEntityImpl();
                        if (ldapConfigurator.getGroupIdAttribute() != null) {
                            group.setId(result.getAttributes().get(ldapConfigurator.getGroupIdAttribute()).get().toString());
                        }
                        if (ldapConfigurator.getGroupNameAttribute() != null) {
                            group.setName(result.getAttributes().get(ldapConfigurator.getGroupNameAttribute()).get().toString());
                        }
                        if (ldapConfigurator.getGroupTypeAttribute() != null) {
                            group.setType(result.getAttributes().get(ldapConfigurator.getGroupTypeAttribute()).get().toString());
                        }
                        groups.add(group);
                    }

                    namingEnum.close();

                    return groups;

                } catch (NamingException e) {
                    throw new FlowableException("Could not find groups " + searchExpression, e);
                }
            }

        });
    }

    protected SearchControls createSearchControls() {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
        return searchControls;
    }
}

根据自己的业务需要,提供用户的管理功能。关键部分:

  • 配置IdmEngineConfiguration参数

  • 实现IdmIdentityService,可继承IdmIdentityServiceImpl

  • 实现UserQuery,可继承UserQueryImpl

  • 实现GroupQuery,可继承GroupQueryImpl

  • 实现PrivilegeQuery,可继承PrivilegeQueryImpl

相当于做自己的权限管理系统的查询客户端。

看完了这篇文章,相信你对“flowable工作流引擎如何实现自定义权限管理”有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!