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