【问题标题】:Creating a custom user store manager in wso2 IS KM 5.7.0 not visible in the drop down of user stores in carbon screen在 wso2 IS KM 5.7.0 中创建自定义用户存储管理器在碳屏幕的用户存储下拉列表中不可见
【发布时间】:2020-02-27 07:20:48
【问题描述】:

我的系统中有一个用户表,其中包含 USER_ID、PASSWORD、EMAIL、STATUS 等列。我想在 wso2 5.7.0 中合并相同的用户表,所以我创建了一个扩展 JDBCUserStoreManager 的自定义用户存储。我已经点击了这个链接:

http://pushpalankajaya.blogspot.com/2013/09/how-to-write-custom-user-store-manager.html

我知道该教程是针对旧版本的 wso2 IS,所以我从这个链接中获取了 pom 文件参考:

https://docs.wso2.com/display/IS570/Writing+a+Custom+User+Store+Manager

然后我在eclipse中成功构建了一个OSGI bundle,并上传到/repository/components/dropins目录下。但仍然在使用 -DosgiConsole 启动服务器(打印捆绑激活日志)时,我没有看到我的捆绑包的捆绑激活日志。而且在尝试添加新用户存储时,我在下拉菜单中看不到 CustomUserStoreManager。

我在这里有什么遗漏吗???任何帮助都将不胜感激。

我当前的 pom.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.wso2.custom.user.store</groupId>
    <artifactId>org.wso2.custom.user.store.CustomUserStoreManager</artifactId>
    <version>1.0.0</version>
    <packaging>bundle</packaging>
    
    <repositories>
        <repository>
            <id>wso2-nexus</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>ignore</checksumPolicy>
            </releases>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.core</artifactId>
            <version>4.4.11</version>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.utils</artifactId>
            <version>4.4.11</version>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.api</artifactId>
            <version>4.4.11</version>
        </dependency>
    </dependencies>

    <build>
    <plugins>
		<plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.3.5</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Private-Package>
                            org.wso2.custom.user.store.internal
                        </Private-Package>
                        <Export-Package>
                            !org.wso2.custom.user.store.internal,
                            org.wso2.custom.user.store.*,
                        </Export-Package>
                        <Import-Package>
                            org.wso2.carbon.*,
                            org.apache.commons.logging.*,
                            org.osgi.framework.*,
                            org.osgi.service.component.*
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>    
    </plugins>
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <inherited>true</inherited>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <version>1.7.2</version>
                <executions>
                    <execution>
                        <id>generate-scr-scrdescriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
     </pluginManagement>
    </build>
</project>

其他java文件:

package org.wso2.custom.user.store;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.user.api.Properties;
import org.wso2.carbon.user.api.Property;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.claim.ClaimManager;
import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.profile.ProfileConfigurationManager;
import org.wso2.carbon.user.core.util.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;


/**
 * Sample User Store Manager Class
 * <p/>
 * This is a sample user store manage for a user table which contains columns -
 * customer_id, customer_name and password
 * <p/>
 * This has been extended the JDBCUserStoreManager class  which is shipped with carbon.user.core
 * bundle and override some methods.
 * <p/>
 * JDBCUserStoreManager can not be used for a user table with contains two columns. Therefore these
 * override method just ensure that reading is done according to the custom schema.
 * Therefore most of the override methods are same as the methods in JDBCUserStoreManager class.
 * <p/>
 * Some functionality has been limited this user table such as tenant aware, salted password
 * value ,creating time of user and etc.
 * <p/>
 * This class only a sample demonstration of writing a custom user store manager. Also anyone can
 * write their own implementation by extending AbstractUserStoreManager or implementing UserStoreManager
 */
public class CustomUserStoreManager extends JDBCUserStoreManager {


    private static Log log = LogFactory.getLog(CustomUserStoreManager.class);

    public CustomUserStoreManager() {
    }

    public CustomUserStoreManager(org.wso2.carbon.user.api.RealmConfiguration realmConfig,
                                  Map<String, Object> properties,
                                  ClaimManager claimManager,
                                  ProfileConfigurationManager profileManager,
                                  UserRealm realm, Integer tenantId)
            throws UserStoreException {
        super(realmConfig, properties, claimManager, profileManager, realm, tenantId, false);
    }

    @Override
    public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {

        if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) {
            log.error("Anonymous user trying to login");
            return false;
        }

        Connection dbConnection = null;
        ResultSet rs = null;
        PreparedStatement prepStmt = null;
        String sqlstmt = null;
        String password = (String) credential;
        boolean isAuthed = false;

        try {
            dbConnection = getDBConnection();
            dbConnection.setAutoCommit(false);
            //paring the SELECT_USER_SQL from user_mgt.xml
            sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER);

            if (log.isDebugEnabled()) {
                log.debug(sqlstmt);
            }

            prepStmt = dbConnection.prepareStatement(sqlstmt);
            prepStmt.setString(1, userName);

            rs = prepStmt.executeQuery();

            if (rs.next()) {
                String storedPassword = rs.getString(2);
                if ((storedPassword != null) && (storedPassword.trim().equals(password))) {
                    isAuthed = true;
                }

            }
        } catch (SQLException e) {
            throw new UserStoreException("Authentication Failure. Using sql :" + sqlstmt);
        } finally {
            DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
        }

        if (log.isDebugEnabled()) {
            log.debug("User " + userName + " login attempt. Login success :: " + isAuthed);
        }

        return isAuthed;

    }

    @Override
    public Date getPasswordExpirationTime(String userName) throws UserStoreException {
        return null;
    }

    protected boolean isValueExisting(String sqlStmt, Connection dbConnection, Object... params)
            throws UserStoreException {
        PreparedStatement prepStmt = null;
        ResultSet rs = null;
        boolean isExisting = false;
        boolean doClose = false;
        try {
            if (dbConnection == null) {
                dbConnection = getDBConnection();
                doClose = true; //because we created it
            }
            if (DatabaseUtil.getStringValuesFromDatabase(dbConnection, sqlStmt, params).length > 0) {
                isExisting = true;
            }
            return isExisting;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
            log.error("Using sql : " + sqlStmt);
            throw new UserStoreException(e.getMessage(), e);
        } finally {
            if (doClose) {
                DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
            }
        }
    }

    public String[] getUserListFromProperties(String property, String value, String profileName)
            throws UserStoreException {
        return new String[0];
    }


    /*@Override
    public Map<String, String> doGetUserClaimValues(String userName, String[] claims,
                                                    String domainName) throws UserStoreException {
        return new HashMap<String, String>();
    }*/

    /*@Override
    public String doGetUserClaimValue(String userName, String claim, String profileName)
            throws UserStoreException {
        return null;
    }*/

    @Override
    public boolean isReadOnly() throws UserStoreException {
        return true;
    }

    @Override
    public void doAddUser(String userName, Object credential, String[] roleList,
                          Map<String, String> claims, String profileName,
                          boolean requirePasswordChange) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    public void doAddRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doDeleteRole(String roleName) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doDeleteUser(String userName) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public boolean isBulkImportSupported() {
        return false;
    }

    @Override
    public void doUpdateRoleName(String roleName, String newRoleName) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doSetUserClaimValue(String userName, String claimURI, String claimValue,
                                    String profileName) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doSetUserClaimValues(String userName, Map<String, String> claims,
                                     String profileName) throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doDeleteUserClaimValue(String userName, String claimURI, String profileName)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    @Override
    public void doUpdateCredentialByAdmin(String userName, Object newCredential)
            throws UserStoreException {
        throw new UserStoreException(
                "User store is operating in read only mode. Cannot write into the user store.");
    }

    public String[] getExternalRoleListOfUser(String userName) throws UserStoreException {
        /*informix user store manager is supposed to be read only and users in the custom user store
          users in the custom user store are only assigned to internal roles. Therefore this method
          returns an empty string.
         */

        return new String[0];
    }

    @Override
    public String[] doGetRoleNames(String filter, int maxItemLimit) throws UserStoreException {
        return new String[0];
    }

    @Override
    public boolean doCheckExistingRole(String roleName) throws UserStoreException {

        return false;
    }

    @Override
    public boolean doCheckExistingUser(String userName) throws UserStoreException {

        return true;
    }

    @Override
    public org.wso2.carbon.user.api.Properties getDefaultUserStoreProperties(){
        Properties properties = new Properties();
        properties.setMandatoryProperties(CustomUserStoreConstants.CUSTOM_UM_MANDATORY_PROPERTIES.toArray
                (new Property[CustomUserStoreConstants.CUSTOM_UM_MANDATORY_PROPERTIES.size()]));
        properties.setOptionalProperties(CustomUserStoreConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.toArray
                (new Property[CustomUserStoreConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.size()]));
        properties.setAdvancedProperties(CustomUserStoreConstants.CUSTOM_UM_ADVANCED_PROPERTIES.toArray
                (new Property[CustomUserStoreConstants.CUSTOM_UM_ADVANCED_PROPERTIES.size()]));
        return properties;
    }
}

    /*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * 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.wso2.custom.user.store;


import org.wso2.carbon.user.api.Property;
import org.wso2.carbon.user.core.UserStoreConfigConstants;
import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;

import java.util.ArrayList;

public class CustomUserStoreConstants {


    //Properties for Read Active Directory User Store Manager
    public static final ArrayList<Property> CUSTOM_UM_MANDATORY_PROPERTIES = new ArrayList<Property>();
    public static final ArrayList<Property> CUSTOM_UM_OPTIONAL_PROPERTIES = new ArrayList<Property>();
    public static final ArrayList<Property> CUSTOM_UM_ADVANCED_PROPERTIES = new ArrayList<Property>();


    static {

        setMandatoryProperty(JDBCRealmConstants.DRIVER_NAME, "oracle.jdbc.driver.OracleDriver", "Full qualified driver name");
        setMandatoryProperty(JDBCRealmConstants.URL, "", "URL of the user store database");
        setMandatoryProperty(JDBCRealmConstants.USER_NAME, "", "Username for the database");
        setMandatoryProperty(JDBCRealmConstants.PASSWORD, "", "Password for the database");

        setProperty(UserStoreConfigConstants.disabled, "false", UserStoreConfigConstants.disabledDescription);

        setProperty("ReadOnly", "true", "Indicates whether the user store of this realm operates in the user read only mode or not");
        setProperty(UserStoreConfigConstants.SCIMEnabled, "false", UserStoreConfigConstants.SCIMEnabledDescription);


        //Advanced Properties (No descriptions added for each property)
        setAdvancedProperty("SelectUserSQL", "SELECT * FROM USER_MASTER WHERE USER_ID=?", "");
        setAdvancedProperty("UserFilterSQL", "SELECT USER_ID FROM USER_MASTER WHERE USER_ID LIKE ?  ORDER BY USER_ID", "");

    }


    private static void setProperty(String name, String value, String description) {
        Property property = new Property(name, value, description, null);
        CUSTOM_UM_OPTIONAL_PROPERTIES.add(property);

    }

    private static void setMandatoryProperty(String name, String value, String description) {
        Property property = new Property(name, value, description, null);
        CUSTOM_UM_MANDATORY_PROPERTIES.add(property);

    }

    private static void setAdvancedProperty(String name, String value, String description) {
        Property property = new Property(name, value, description, null);
        CUSTOM_UM_ADVANCED_PROPERTIES.add(property);

    }


}

package org.wso2.custom.user.store.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.custom.user.store.CustomUserStoreManager;
import org.wso2.carbon.user.api.UserStoreManager;


/**
 * @scr.component name="custom.user.store.manager.dscomponent" immediate=true
 * @scr.reference name="user.realmservice.default"
 * interface="org.wso2.carbon.user.core.service.RealmService"
 * cardinality="1..1" policy="dynamic" bind="setRealmService"
 * unbind="unsetRealmService"
 */
public class CustomUserStoreMgtDSComponent {
    private static Log log = LogFactory.getLog(CustomUserStoreMgtDSComponent.class);
    private static RealmService realmService;

    protected void activate(ComponentContext ctxt) {

        CustomUserStoreManager customUserStoreManager = new CustomUserStoreManager();
        ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), customUserStoreManager, null);
        log.info("CustomUserStoreManager bundle activated successfully..");
    }

    protected void deactivate(ComponentContext ctxt) {
        if (log.isDebugEnabled()) {
            log.debug("CustomUserStoreManager is deactivated ");
        }
    }

    protected void setRealmService(RealmService rlmService) {
          realmService = rlmService;
    }

    protected void unsetRealmService(RealmService realmService) {
        realmService = null;
    }

    public static RealmService getRealmService() {
        return realmService;
    }
}

【问题讨论】:

    标签: wso2 osgi wso2is wso2carbon osgi-bundle


    【解决方案1】:

    您在 pom.xml 文件中指定的 carbon 内核版本不是 Identity Server 5.7.0[1] 中使用的版本,使用版本为 4.4.35。

    另外,请尝试将 pom 文件中的 instructions 标记替换为以下内容

                   <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Private-Package>
                            org.wso2.custom.user.store.internal
                        </Private-Package>
                        <Export-Package>
                            !org.wso2.custom.user.store.internal,
                            org.wso2.custom.user.store.*,
                        </Export-Package>
                     <DynamicImport-Package>*</DynamicImport-Package>
                    </instructions>
    

    不建议使用 DynamicImport-Package,但它可能会帮助您调试问题。

    [1]。 https://github.com/wso2/product-is/blob/v5.7.0/pom.xml#L1859

    【讨论】:

    【解决方案2】:

    终于成功了。谢谢你指导我。我参考了以下链接并对我的代码进行了更改:

    https://github.com/wso2/product-is/tree/master/modules/samples/user-mgt/sample-custom-user-store-manager

    由于没有更新的教程/示例,我想在这里发布我更新的代码:

    pom.xml 文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
        <modelVersion>4.0.0</modelVersion>
        <version>1.0</version>
        <packaging>bundle</packaging>
        <dependencies>
            <dependency>
    		    <groupId>org.wso2.carbon</groupId>
    		    <artifactId>org.wso2.carbon.user.core</artifactId>
    		    <version>4.4.35</version>
    		</dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.user.api</artifactId>
                <version>4.4.35</version>
            </dependency>
            <dependency>
                <groupId>org.apache.felix</groupId>
                <artifactId>org.apache.felix.scr.ds-annotations</artifactId>
                <scope>provided</scope>
                <version>1.2.10</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>maven-bundle-plugin</artifactId>
                    <version>3.2.0</version>
                    <extensions>true</extensions>
                    <configuration>
                        <instructions>
                            <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
                            <Bundle-Name>${pom.artifactId}</Bundle-Name>
                            <Private-Package>
                                org.wso2.sample.user.store.manager.internal
                            </Private-Package>
                            <Export-Package>
                                !org.wso2.sample.user.store.manager.internal,
                                org.wso2.sample.user.store.manager.*,
                            </Export-Package>
                            <Import-Package>
                                javax.servlet; version=2.4.0,
                                javax.servlet.http; version=2.4.0,
                                org.wso2.carbon.base.*,
                                org.wso2.carbon.user.core.*,
                                <!--                            org.apache.lucene.*,-->
                                *;resolution:=optional
                            </Import-Package>
                            <DynamicImport-Package>*</DynamicImport-Package>
                        </instructions>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <groupId>org.wso2.sample.user.store.manager</groupId>
        <artifactId>CustomJDBCUserStoreManager</artifactId>
    </project>

    还有 java 文件:

    JDBCUserStoreManager.java:

    package org.wso2.sample.user.store.manager;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.wso2.carbon.CarbonConstants;
    import org.wso2.carbon.user.api.*;
    import org.wso2.carbon.user.core.UserRealm;
    import org.wso2.carbon.user.core.UserStoreException;
    import org.wso2.carbon.user.core.claim.ClaimManager;
    import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
    import org.wso2.carbon.user.core.profile.ProfileConfigurationManager;
    import org.wso2.carbon.user.core.util.DatabaseUtil;
    
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Date;
    import java.util.Map;
    
    
    /**
     * Sample User Store Manager Class
     */
    public class CustomJDBCUserStoreManager extends org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager {
    
         private static Log log = LogFactory.getLog(CustomJDBCUserStoreManager.class);
    
        public CustomJDBCUserStoreManager() {
    
        }
    
        public CustomJDBCUserStoreManager(org.wso2.carbon.user.api.RealmConfiguration realmConfig,
                Map<String, Object> properties,
                ClaimManager claimManager,
                ProfileConfigurationManager profileManager,
                UserRealm realm, Integer tenantId)
                        throws UserStoreException {
            super(realmConfig, properties, claimManager, profileManager, realm, tenantId, false);
            }
    
        @Override
        public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {
    
            log.info("CustomUserStoreManager:: doAuthenticate:: Entry");
    
            if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) {
                log.error("Anonymous user trying to login");
                return false;
            }
    
            Connection dbConnection = null;
            ResultSet rs = null;
            PreparedStatement prepStmt = null;
            String sqlstmt = null;
            String password = (String) credential;
            boolean isAuthed = false;
    
            try {
                dbConnection = getDBConnection();
                dbConnection.setAutoCommit(false);
                //paring the SELECT_USER_SQL from user_mgt.xml
                sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER);
    
                if (log.isDebugEnabled()) {
                    log.debug(sqlstmt);
                }
    
                log.warn("SQL:: "+sqlstmt);
                log.warn("Username:: "+userName+"Password:: "+password);
    
                prepStmt = dbConnection.prepareStatement(sqlstmt);
                prepStmt.setString(1, userName);
    
                rs = prepStmt.executeQuery();
    
                if (rs.next()) {
                    String storedPassword = rs.getString(2);
                    log.warn("Stored Password:: "+storedPassword);
                    if ((storedPassword != null) && (storedPassword.trim().equals(password))) {
                        isAuthed = true;
                    }
    
                }
            } catch (SQLException e) {
                throw new UserStoreException("Authentication Failure. Using sql :" + sqlstmt);
            } finally {
                DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
            }
    
            if (log.isDebugEnabled()) {
                log.debug("User " + userName + " login attempt. Login success :: " + isAuthed);
            }
            log.info("CustomUserStoreManager:: doAuthenticate:: Exit isAuthed::"+isAuthed);
            return isAuthed;
    
        }
    
        @Override
        public Date getPasswordExpirationTime(String userName) throws UserStoreException {
            return null;
        }
    
        protected boolean isValueExisting(String sqlStmt, Connection dbConnection, Object... params)
                throws UserStoreException {
            PreparedStatement prepStmt = null;
            ResultSet rs = null;
            boolean isExisting = false;
            boolean doClose = false;
            try {
                if (dbConnection == null) {
                    dbConnection = getDBConnection();
                    doClose = true; //because we created it
                }
                if (DatabaseUtil.getStringValuesFromDatabase(dbConnection, sqlStmt, params).length > 0) {
                    isExisting = true;
                }
                return isExisting;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
                log.error("Using sql : " + sqlStmt);
                throw new UserStoreException(e.getMessage(), e);
            } finally {
                if (doClose) {
                    DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
                }
            }
        }
    
        public String[] getUserListFromProperties(String property, String value, String profileName)
                throws UserStoreException {
            return new String[0];
        }
    
    
        /*@Override
        public Map<String, String> doGetUserClaimValues(String userName, String[] claims,
                                                        String domainName) throws UserStoreException {
            return new HashMap<String, String>();
        }*/
    
        /*@Override
        public String doGetUserClaimValue(String userName, String claim, String profileName)
                throws UserStoreException {
            return null;
        }*/
    
        @Override
        public boolean isReadOnly() throws UserStoreException {
            return true;
        }
    
        @Override
        public void doAddUser(String userName, Object credential, String[] roleList,
                              Map<String, String> claims, String profileName,
                              boolean requirePasswordChange) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        public void doAddRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doDeleteRole(String roleName) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doDeleteUser(String userName) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public boolean isBulkImportSupported() {
            return false;
        }
    
        @Override
        public void doUpdateRoleName(String roleName, String newRoleName) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doSetUserClaimValue(String userName, String claimURI, String claimValue,
                                        String profileName) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doSetUserClaimValues(String userName, Map<String, String> claims,
                                         String profileName) throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doDeleteUserClaimValue(String userName, String claimURI, String profileName)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        @Override
        public void doUpdateCredentialByAdmin(String userName, Object newCredential)
                throws UserStoreException {
            throw new UserStoreException(
                    "User store is operating in read only mode. Cannot write into the user store.");
        }
    
        public String[] getExternalRoleListOfUser(String userName) throws UserStoreException {
            /*informix user store manager is supposed to be read only and users in the custom user store
              users in the custom user store are only assigned to internal roles. Therefore this method
              returns an empty string.
             */
    
            return new String[0];
        }
    
        @Override
        public String[] doGetRoleNames(String filter, int maxItemLimit) throws UserStoreException {
            return new String[0];
        }
    
        @Override
        public boolean doCheckExistingRole(String roleName) throws UserStoreException {
    
            return false;
        }
    
        @Override
        public boolean doCheckExistingUser(String userName) throws UserStoreException {
    
            return true;
        }
    
        @Override
        public org.wso2.carbon.user.api.Properties getDefaultUserStoreProperties(){
            Properties properties = new Properties();
            properties.setMandatoryProperties(CustomJDBCUserStoreManagerConstants.CUSTOM_UM_MANDATORY_PROPERTIES.toArray
                    (new Property[CustomJDBCUserStoreManagerConstants.CUSTOM_UM_MANDATORY_PROPERTIES.size()]));
            properties.setOptionalProperties(CustomJDBCUserStoreManagerConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.toArray
                    (new Property[CustomJDBCUserStoreManagerConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.size()]));
            properties.setAdvancedProperties(CustomJDBCUserStoreManagerConstants.CUSTOM_UM_ADVANCED_PROPERTIES.toArray
                    (new Property[CustomJDBCUserStoreManagerConstants.CUSTOM_UM_ADVANCED_PROPERTIES.size()]));
            return properties;
        }
    
    
    }
    

    CustomJDBCUserStoreManagerConstants.java:

    /*
     * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
     *
     * 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.wso2.sample.user.store.manager;
    
    
    import org.wso2.carbon.user.api.Property;
    import org.wso2.carbon.user.core.UserStoreConfigConstants;
    import org.wso2.carbon.user.core.jdbc.JDBCRealmConstants;
    
    import java.util.ArrayList;
    
    public class CustomJDBCUserStoreManagerConstants {
    
    
        //Properties for Read Active Directory User Store Manager
        public static final ArrayList<Property> CUSTOM_UM_MANDATORY_PROPERTIES = new ArrayList<Property>();
        public static final ArrayList<Property> CUSTOM_UM_OPTIONAL_PROPERTIES = new ArrayList<Property>();
        public static final ArrayList<Property> CUSTOM_UM_ADVANCED_PROPERTIES = new ArrayList<Property>();
    
        static {
            setMandatoryProperty(JDBCRealmConstants.DRIVER_NAME, "", "Full qualified driver name");
            setMandatoryProperty(JDBCRealmConstants.URL, "", "URL of the user store database");
            setMandatoryProperty(JDBCRealmConstants.USER_NAME, "", "Username for the database");
            setMandatoryProperty(JDBCRealmConstants.PASSWORD, "", "Password for the database");
    
            setProperty(UserStoreConfigConstants.disabled, "false", UserStoreConfigConstants.disabledDescription);
    
            setProperty("ReadOnly", "true", "Indicates whether the user store of this realm operates in the user read only mode or not");
            setProperty(UserStoreConfigConstants.SCIMEnabled, "false", UserStoreConfigConstants.SCIMEnabledDescription);
    
    
            //Advanced Properties (No descriptions added for each property)
            setAdvancedProperty(JDBCRealmConstants.SELECT_USER, "SELECT * FROM WSO2_USER_MASTER WHERE USER_ID=?", "");
            setAdvancedProperty(JDBCRealmConstants.GET_USER_FILTER, "SELECT USER_ID FROM WSO2_USER_MASTER WHERE USER_ID LIKE ?  ORDER BY USER_ID", "");
    
        }
    
        private static void setProperty(String name, String value, String description) {
            Property property = new Property(name, value, description, null);
            CUSTOM_UM_OPTIONAL_PROPERTIES.add(property);
    
        }
    
        private static void setMandatoryProperty(String name, String value, String description) {
            Property property = new Property(name, value, description, null);
            CUSTOM_UM_MANDATORY_PROPERTIES.add(property);
    
        }
    
        private static void setAdvancedProperty(String name, String value, String description) {
            Property property = new Property(name, value, description, null);
            CUSTOM_UM_ADVANCED_PROPERTIES.add(property);
    
        }
    
    
    }
    

    CustomJDBCUserStoreMgtDSComponent:

    package org.wso2.sample.user.store.manager.internal;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.osgi.service.component.ComponentContext;
    import org.wso2.carbon.user.api.UserStoreManager;
    import org.wso2.carbon.user.core.service.RealmService;
    import org.wso2.sample.user.store.manager.CustomJDBCUserStoreManager;
    import org.osgi.service.component.annotations.Activate;
    import org.osgi.service.component.annotations.Component;
    import org.osgi.service.component.annotations.Deactivate;
    import org.osgi.service.component.annotations.Reference;
    import org.osgi.service.component.annotations.ReferenceCardinality;
    import org.osgi.service.component.annotations.ReferencePolicy;
    
    
    @Component(
            name = "custom.authenticator.dscomponent",
            immediate = true
    
    )
    public class CustomJDBCUserStoreMgtDSComponent {
        private static Log log = LogFactory.getLog(CustomJDBCUserStoreMgtDSComponent.class);
        private static RealmService realmService;
    
        @Activate
        protected void activate(ComponentContext ctxt) {
    
            CustomJDBCUserStoreManager customUserStoreManager = new CustomJDBCUserStoreManager();
            ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), customUserStoreManager, null);
            log.info("CustomUserStoreManager bundle activated successfully..");
        }
    
        @Deactivate
        protected void deactivate(ComponentContext ctxt) {
            if (log.isDebugEnabled()) {
                log.debug("Custom User Store Manager is deactivated ");
            }
        }
    
        @Reference(
                name = "RealmService",
                service = org.wso2.carbon.user.core.service.RealmService.class,
                cardinality = ReferenceCardinality.MANDATORY,
                policy = ReferencePolicy.DYNAMIC,
                unbind = "unsetRealmService")
        protected void setRealmService(RealmService rlmService) {
              realmService = rlmService;
        }
    
        protected void unsetRealmService(RealmService realmService) {
            realmService = null;
        }
    }
    

    【讨论】:

    • 最后这段代码似乎工作了。现在我正在激活我的捆绑包,并且在碳屏幕中,我可以在下拉菜单中看到自定义用户商店管理器。所以我添加了一个带有自定义用户存储管理器的新用户存储。我只能看到碳屏幕中的用户为红色,但我的身份验证失败。我得到这个异常:{“error_description”:“从用户存储验证用户时出错”,“error”:“invalid_grant”}
    • @Buddhima Udaranga 你能指导我吗??
    • 我还添加了日志来检查问题,但它没有打印在 wso2carbon.log 中。顺便说一句,我在 log4j.properties 中包含以下行: log4j.logger.org.wso2.sample.user.store.manager.CustomJDBCUserStoreManager=INFO,WARN,ERROR,DEBUG
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多