Keycloak CustomUserStorageProvider always returns “invalid_user_credentials” error

I am currently working on integrating Keycloak with a custom user storage provider. I have implemented a CustomUserStorageProvider to authenticate users against my own database via HTTP requests. However, whenever I try to log in, Keycloak always returns an “invalid_user_credentials” error.

when i try to log in using Keycloak, I always receive an “invalid_user_credentials” error. However, the backend endpoints are working correctly when tested via Postman. Here are the logs from Keycloak:

2024-06-28 12:05:30,244 WARN [org.keycloak.events] (executor-thread-3) type=”LOGIN_ERROR”, realmId=”90cbb49d-93c0-43db-bfb0-13faf3b9c1af”, realmName=”master”, clientId=”nodum_client”, userId=”1cfff481-c734-400a-b2a1-532352396424″, ipAddress=”0:0:0:0:0:0:0:1″, error=”invalid_user_credentials”, auth_method=”openid-connect”, auth_type=”code”, redirect_uri=”http://127.0.0.1:5500/index.html”, code_id=”13b5748a-5ef8-4791-b410-30102cf55b29″, username=”fcaimi”

i think that the getUserByUsername is returning a valid user, and though the problema was in the isValid method, but i change it to return true and the problem is still there.

im running keycloak on my localHost and the keycloak version is 25.0.1
the servlet with the endpoints is also in localHost (different ports of course).

this is my implementation of the customUserStorageProvider:

package uy.com.nodum.keycloak;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.keycloak.component.ComponentModel;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialInputValidator;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.user.UserLookupProvider;
import com.fasterxml.jackson.databind.ObjectMapper;



public class CustomUserStorageProvider implements UserStorageProvider, UserLookupProvider, CredentialInputValidator {

        private static final String UTF_8 = "UTF-8";
        private KeycloakSession session;
        private ComponentModel model;
        private String backendUrl = "http://localhost:8080/keycloakServlet/METest"; 
        private ObjectMapper objectMapper = new ObjectMapper();

        public CustomUserStorageProvider(KeycloakSession session, ComponentModel model) {
            this.session = session;
            this.model = model;
        }


        public void close() {
            // Cleanup resources if needed
        }

        @Override
        public UserModel getUserById(RealmModel realm,  String id) {
            return null;
        }
        
        public UserModel getUserByEmail(RealmModel realm,String mail){
            return null;
            
        }

        @Override
        public UserModel getUserByUsername(RealmModel realm, String username) {
            try {
                URL url = new URL(backendUrl + "/users/username?username=" + username);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("Content-Type", "application/json");

                int status = con.getResponseCode();
                if (status == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    StringBuilder content = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        content.append(inputLine);
                    }
                    in.close();
                    con.disconnect();

                    User user = objectMapper.readValue(content.toString(), User.class);
                    if (user != null) {
                        return mapUser(realm, user);
                    }
                } else {
                    con.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private UserModel mapUser(RealmModel realm, User user) {
            return new CustomUser.Builder(session, realm, model, user.getUsername())
                    .email(user.getEmail())
                    .firstName(user.getFirstName())
                    .lastName(user.getLastName())
                    .id(user.getId())  // Configurar el ID aquí
                    .build();
        }

       
        public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
            return supportsCredentialType(credentialType);
        }

      
        public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) {
            if (!supportsCredentialType(credentialInput.getType())) {
                System.out.println("Credential type not supported: " + credentialInput.getType());
                return false;
            }
            try {
                String urlStr = String.format("%s/users/validate?username=%s&password=%s",
                        backendUrl, 
                        URLEncoder.encode(user.getUsername(), UTF_8), 
                        URLEncoder.encode(credentialInput.getChallengeResponse(), UTF_8));
                System.out.println("Response code from backend: " + credentialInput.getChallengeResponse());
                URL url = new URL(urlStr);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json");

                int status = con.getResponseCode();
                System.out.println("Response code from backend: " + status);
                con.disconnect();

                return status == 200;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        
        public boolean supportsCredentialType(String credentialType) {
            return true;
        }

        public List<UserModel> getUsers(RealmModel realm) {
            // Implementación si es necesario
            return null;
        }

     
        public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
            // Implementación si es necesario
            return null;
        }

        public List<UserModel> searchForUser(String search, RealmModel realm) {
            // Implementación si es necesario
            return null;
        }

        public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
            // Implementación si es necesario
            return null;
        }

      
        public List<UserModel> searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) {
            // Implementación si es necesario
            return null;
        }

    
        public UserModel getUserByEmail(String arg0, RealmModel arg1) {
            // TODO Auto-generated method stub
            return null;
        }


    }

    class User {
        private String username;
        private String firstName;
        private String lastName;
        private String email;
        private String password;
        private String id;

        // Constructor, getters y setters
        public User() {}

        public User(String id, String username, String firstName, String lastName, String email, String password) {
            this.id = id;
            this.username = username;
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.password = password;
        }

        public String getUsername() {
            return username;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public String getEmail() {
            return email;
        }

        public String getPassword() {
            return password;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }

    class UserCredentials {
        private String username;
        private String password;

        // Constructor, getters y setters
        public UserCredentials() {}

        public UserCredentials(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }
    }

i change the isValid method tu return true.
i try to debug the storage from eclipse with the remote java application in my localhost:8787, but it didnt recognize the breakpoints.
i dont know what else to try because im not getting a lot of help of the logs and cant debug de storage

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật