Keycloak
allows us to create users through admin console. But in few scenarios, we might
not want our users to know about the underlying authentication mechanisms. In
those scenarios, we may need to create users from our application, rather than
doing it from the admin console of keycloak.
In
this post, let us discuss on how to create users in keycloak by using their REST services.
Code snippet
KeycloakSecurityContext session = (KeycloakSecurityContext)httpreq.getAttribute(KeycloakSecurityContext.class.getName());
String req =
“http://localhost:8081/auth/admin/realms/<REALM_NAME>/users";
String jsonBody =
"{\"username\":\""+request.getEmailId()+"\",\"enabled\":\"true\",\"firstName\":\""+request.getFirstName()+"\",\"lastName\":\""+request.getLastName()+"\",\"email\":\""+request.getEmailId()+"\,\"credentials\":[{\"type\":\"password\",\"value\":\"password\"}]}";
ClientRequest clientRequest = new ClientRequest(req);
clientRequest.body("application/json",
jsonBody);
clientRequest.accept("application/json");
clientRequest.header("Authorization", "Bearer
" + session.getTokenString());
ClientResponse clientresponse = clientRequest.post(String.class);
jsonBody : Contains the attributes of the user that needs to be created.
Username - Unique
name(can be a name or an email id)
Enabled - this
flag has to be set to true (otherwise , the user created will not be in use)
firstName - First
name of the user
lastName - Last
name of the user
email - Email
id of the user
credentials - This
is an object with value and type. Type implies the type of security to be used for the user login. Value
implies the actual password to be set to the user
No comments:
Post a Comment