Search code examples
angularkeycloakangular7

Create user on keycloak with Angular 7 by REST API


I have a little problem to register a user on Keycloak.

I use keycloak-admin-client:

let keycloakAdminClient = require('keycloak-admin-client');

When the client tries to create a user, the server says 403 forbidden.

keycloakAdminClient(clientSettings)
  .then((clients) => {
    console.log('[newRegistration - keycloakAdminClient] init success');
    console.log(clients.token);
    clients.users.create(environment.KEYCLOAK_REALM, newKeycloakUser)
      .then((createdUser) => {
        console.log('[newRegistration - keycloakAdminClient - client.users.create] success - createdUser = ' + createdUser);
        // findNewUserId(newKeycloakUser.username);
        return newKeycloakUser.username;
      })
      .catch((err) => {

        console.log('[newRegistration - keycloakAdminClient - client.users.create] error - code = ', err);
      });
  })
  .catch((err) => {
    console.log('[newRegistration - keycloakAdminClient] init error - code = ', err);
  });
console.log('[newRegistration] END');
};

This is the settings of client:

 export const environment = {
  production: false,
  KEYCLOAK_URL: 'http://10.10.15.35:8080/auth',
  KEYCLOAK_REALM: 'baulogistik_test',
  KEYCLOAK_CLIENTID: 'angular-frontend',
  BACKEND_URL: 'http://10.10.15.35:8080/api',
  CLIENT_SECRET: '296f7a0f-a0f5-4395-a120-ece8565bbce1'
};

const clientSettings = {
    production: environment.production,
    baseUrl: environment.KEYCLOAK_URL,
    client_id: environment.KEYCLOAK_CLIENTID,
    realmName: environment.KEYCLOAK_REALM,
    grant_type: 'client_credentials',
    client_secret: environment.CLIENT_SECRET
}

I can log in with the client via the secret key and get an accessToken.

The client has admin role.

Role Settings on keycloak

client settings

Have anybody an advice for me? Thanks!


Solution

  • I got it. You have to add the roles from the realm-management client to your admin role.

    enter image description here

    After that, a user must have the admin role. Then the clientSettings has to be extended in the Angular app:

    • Add username and password of your admin user

    • Modify grant_type to password

       const clientSettings = {
       production: environment.production,
       baseUrl: environment.KEYCLOAK_URL,
       client_id: environment.KEYCLOAK_CLIENTID,
       realmName: environment.KEYCLOAK_REALM,
       grant_type: 'password',//'client_credentials',
       username: environment.username,
       password: environment.password,
       client_secret: environment.CLIENT_SECRET