Keycloak用户存储SPI身份验证流程

时间:2019-08-31 04:39:58

标签: java keycloak keycloak-services

从登录时的前端应用程序将用户重定向到Keycloak页面。用户已通过外部服务进行了身份验证

我已经实现了keycloak用户存储SPI流。它根据外部来源进行身份验证。 Keycloak已使用外部存储属性进行了更新,如果通过getUserByUsername方法进行了更新,它将可以正常工作。

我正在验证isValid方法中的userValidation并更新UserModel和LocalHashMap中的userAttributes。

从日志中,我看到UserStoreProviderFactory创建了两个实例来对一个事务/登录进行身份验证

我的问题是,Keycloak是否为一个身份验证流创建UserStorageProvider的两个实例。由于它多次调用,因此必须对在isValid方法上创建的UserModel进行缓存,并在第二次再次检索它,可以避免吗?

为什么在第一次userStorageProvider调用中多次调用getUserByUserName()方法

            UserStorageProviderFactory
                 -> Creates instance of UserStorageProvider
                    -> UserStorage provider calls getUserById method
                    -> UserStorage provider calls getUserByUserName method
                    -> UserStorage provider calls isValid method
                                 on true, keycloak 
            UserStorageProviderFactory
                 -> Creates instance of UserStorageProvider
                    -> UserStorage provider calls getUserById method
                    -> UserStorage provider calls getUserByUserName method
                           returns UserModel


 @Override
public UserModel getUserById(String id, RealmModel realm) {
    logger.debug("__ ########## getUserById  ID:" + "ID: " + id + ":REALM:" + realm);
    StorageId storageId = new StorageId(id);
    /**
     * StorageId.getExternalId() method is invoked to obtain 
     * the username embeded in the id parameter
     */
    String username = storageId.getExternalId();
    System.out.println("Name:" + username);
    return getUserByUsername(username, realm);
}

/***
 * From UserLookupProvider
 * This method is invoked by the Keycloak login page when a user logs in
 */
@Override
public UserModel getUserByUsername(String username, RealmModel realm) {
    logger.debug("__ %%%%%%%%%% getUserByUsername ID:" + username + ":REALM:" + realm);
    logger.debug("Provider Num:" + this.randomNum);
    UserModel userModel = loadedUsers.get(username);

    UserModel local = session.userLocalStorage().getUserByUsername(username, realm);
    logger.debug("*#@#$ local session:" + local);

    if (userModel == null) {
        logger.debug("In NULLLLLLLLLLLLLLLLLLL ");
        userModel = createUserModel(realm, username);
        // set for demo...
        userModel.setSingleAttribute("externalId", Integer.toString(10));
    } else {
        logger.debug("__ ELSEEEEEEEEEEEEEE getUserByUsername sku:" +  userModel.getFirstAttribute("sku"));
        userModel.setSingleAttribute("externalId", Integer.toString(12));
    }

    return userModel;
}

public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
    logger.debug("__ , 1111111111 isValid:input type:" +  input.getType() + ":userName:" + user.getUsername());

    UserCredentialModel cred = (UserCredentialModel)input;

    if (!supportsCredentialType(input.getType()) 
            || !(input instanceof UserCredentialModel)) {
        logger.warn("__, credentialType: " + input.getType() + ": NOT supported");
        return false;
    }

    UserDTO model = new UserDTO();
    model.setEmailId(user.getUsername());
    model.setPassword(cred.getValue());

    try {
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target(properties.getProperty("userUrl"));
        Response response = target.request().post(
                Entity.entity(model, "application/json"));

        ResponseDTO<UserResponseDTO> responseDto = response.readEntity(new GenericType<ResponseDTO<UserResponseDTO>>() {});
        logger.debug("__ , !!!!!!!!!!! json response:" +  responseDto);
        logger.debug("!!!! Provider Num:" + this.randomNum);
        if (responseDto.getCode() == 200) {
            UserResponseDTO userResponseDto = responseDto.getData();
            UserDetailsDTO userDetailsDto = userResponseDto.getDetails();
            user.setEmail(userDetailsDto.getEmailId());
            user.setFirstName(userDetailsDto.getFirstName());

            logger.debug("!!!!@@@@@@@@ Provider Num:" + this.randomNum);
            logger.debug("__ , returning success from isValid:" + user.getUsername() +":::"); 
            loadedUsers.put(user.getUsername(), user);
            return true;
        }
        response.close();

    } catch(Exception ex) {
        logger.error("Exception Occured accessing:", ex);
    }

    return false;

}

日志(显示调用getUserById()和getUserByUserName()方法的次数,UserStorageFactory实例化两次UserStorageProvider实例)

  

2019-08-30 08:49:26,273调试[org.test.keycloak.userstore.factory.TestUserStoreProviderFactory](默认任务2)userURL:http://localhost:8280/login

     

2019-08-30 08:49:26,283调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95 -6b5d-4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:26,291调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:26,319 DEBUG [org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)在NULLLLLLLLLLLLLLLLLLL中   2019-08-30 08:49:26,951调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__,!!!!!!!!!!! json响应:消息:登录:状态:成功   2019-08-30 08:49:26,952调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95-6b5d- 4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:26,953信息[stdout](默认任务2)名称:test@gmail.com

     

2019-08-30 08:49:26,960调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)____ %%%%%%%%%% getUserByUsername ID:test@gmail.com :REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:26,962调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)LOADEDUSERS,密钥大小:0   2019-08-30 08:49:26,962调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)在NULLLLLLLLLLLLLLLLLLL中   2019-08-30 08:49:26,965调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__,从isValid:test@gmail.com :::

返回成功      

2019-08-30 08:49:26,966调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95 -6b5d-4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:26,986调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:27,022调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ELSEEEEEEEEEEEEEE getUserByUsername sku:1

     

2019-08-30 08:49:27,056调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95 -6b5d-4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:27,059调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:27,059调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)LOADEDUSERS,密钥大小:1   2019-08-30 08:49:27,059调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ELSEEEEEEEEEEEEEE getUserByUsername sku:1   2019-08-30 08:49:27,061调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a

     

2019-08-30 08:49:27,071调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95 -6b5d-4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:27,073调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:27,073调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ELSEEEEEEEEEEEEEE getUserByUsername sku:1

     

2019-08-30 08:49:29,421调试[org.test.keycloak.userstore.factory.TestUserStoreProviderFactory](默认任务2)userURL:http://localhost:8280/login   2019-08-30 08:49:29,422调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95-6b5d- 4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:29,432调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:29,432调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)在NULLLLLLLLLLLLLLLLLLL中   2019-08-30 08:49:29,581调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ ########## getUserById ID:ID:f:4a65ac95-6b5d- 4508-b7ec-348ae1da619d:test@gmail.com:REALM:org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a   2019-08-30 08:49:29,581调试[org.test.keycloak.userstore.TestUserStoreProvider](默认任务2)__ %%%%%%%%%% getUserByUsername ID:test@gmail.com:REALM: org.keycloak.models.cache.infinispan.RealmAdapter@64ddda7a

任何可以帮助我解决/理解工作流程的建议/技巧,将不胜感激!

1 个答案:

答案 0 :(得分:0)

根据文档,其状态

  

UserProvider-请记住,提供程序类实例在每个事务中创建一次,并在事务完成后关闭。

但是在应用程序中它被多次调用,因为

  • 首先,创建一个UserProvider实例以通过登录流程。在此流程上更新的UserModel,除非已缓存/存储,否则将无法在外部使用

  • 第二,使用以下端点创建UserProvider实例以创建令牌。从getUserByUserName方法()返回UserModel对象。     “ http://localhost:8180/auth/realms/myapp/protocol/openid-connect/token

要存储具有自定义属性的UserModel,

this.session.userLocalStorage().addUser(realm, user.getUsername());

    @Override
public UserModel addUser(RealmModel realm, String username) {
    // userModel returned should be subclassed or instance of AbstractUserAdapterFederatedStorage
    return this.myUserModel;

}

要更新存储在localStorage中的UserModel,应删除并添加现有用户。

要删除用户,必须设置FederationLink。

//ComponentModel ID of the provider. This sets a link between the provider and the imported user
user.setFederationLink(this.model.getId());