Search code examples
node.jskeycloak

I can't login to Keycloak with Node


I want to login to Keycloak with Node. My Keycloak instance runs on a container in a virtual machine. I am using the following code:

const axios = require('axios');

function loginToKeycloak(username, password, clientId, realmName) {
    const keycloakUrl = 'https://<ip of my virtual machine>:8443/auth/realms/';
    const tokenEndpoint = `${keycloakUrl}${realmName}/protocol/openid-connect/token`;

    const data = {
        grant_type: 'password',
        client_id: clientId,
        username,
        password,
    };

    axios.post(tokenEndpoint, new URLSearchParams(data), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }), // Ignore self-signed certificate
    })
        .then((response) => {
            console.log('Login successful');
            console.log('Access Token:', response.data.access_token);
        })
        .catch((error) => {
            console.error('Login failed:', error.response ? error.response.data : error.message);
        });
}

loginToKeycloak('myUser', 'myPassword!', 'myClient', 'myRealm');

The problem is that I get the following error:

'RESTEASY003210: Could not find resource for full path: https://<ip of my virtual machine>:8443/auth/realms/realm1/protocol/openid-connect/token'

If I type

https://<ip of my virtual machine>:8443/

in the searchbar of my browser I can view Keyclock's home page. So apparently the address is correct.


Solution

  • The problem was the substring "auth", that must be removed. Therefore this line:

    const keycloakUrl = 'https://<ip of my virtual machine>:8443/auth/realms/';
    

    must be replaced with

    const keycloakUrl = 'https://<ip of my virtual machine>:8443/realms/';