Keycloak Java. Try to create a new user with set password - java

Keycloak 11.0.
I am trying to create a new user in Keycloak via admin REST endpoint of Keycloak server.
I am facing stack trace on Keycloak server as below.
0 8:59:40,744 ERROR [org.keycloak.services.error.KeycloakErrorHandler] (default task-4) Uncaught server error: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<org.keycloak.representations.idm.CredentialRepresentation>` out of VALUE_STRING token
at [Source: (io.undertow.servlet.spec.ServletInputStreamImpl); line: 1, column: 141] (through reference chain: org.keycloak.representations.idm.UserRepresentation["credentials"])
My code is as below.
private void sendCreateUserRequest(UserEntity userEntity, KeycloakTokenModel keycloakTokenModel) throws JsonProcessingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(keycloakTokenModel.getAccessToken());
JsonObject properties = new JsonObject();
properties.addProperty(FIRST_NAME, userEntity.getFirstName());
properties.addProperty(LAST_NAME, userEntity.getLastName());
properties.addProperty(EMAIL, userEntity.getEmail());
properties.addProperty(ENABLED, DEFAULT_ENABLED_OPTION);
properties.addProperty(USERNAME, userEntity.getEmail());
String credentialsArray = mapToCredentialsArray(userEntity.getPassword());
properties.addProperty(CREDENTIALS, credentialsArray);
String propertiesString = properties.toString();
HttpEntity<String> request = new HttpEntity<>(propertiesString, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(userEndpoint, request, String.class);
}
In debugger I see
propertiesString =
{
"firstName":null,
"lastName":null,
"email":"Tester_Testerov#some.com",
"enabled":"true",
"username":"Tester_Testerov#some.com",
"credentials":
"[
{\"value\":\"verystrongpassword4\",\"type\":\"password\",\"temporary\":false}
]"
}
But without that line String credentialsArray = mapToCredentialsArray(userEntity.getPassword()); it works but I want to set credential to user in this request. Please, help

It is just bad formatted json. See that your array starts and ends with " and this is invalid syntax for json arrays. I think properties.addProperty(CREDENTIALS, credentialsArray); escapes your array with " character.

Related

how to insert hashtag to request link

i need to insert # symbol in the api request. official documentation transforms https://api.brawlstars.com/v1/players/#2JV9PR99Y to https://api.brawlstars.com/v1/players/%232JV9PR99Y.
so if i send request with %23 i will get 404 Not Found: [{"reason":"notFound","message":"Not found with tag %232JV9PR99Y"}] but with postman i can send requests with %23 replace #. if if send request with # it just returns null json body.
my code:
public Player showPlayerInfo(String playerTag) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer " + bearerToken);
HttpEntity<String> request = new HttpEntity<String>(headers);
String url = "https://api.brawlstars.com/v1/players/%232JV9PR99Y"; // testing
System.out.println(url);
ResponseEntity<Player> response = restTemplate.exchange(url, HttpMethod.GET, request, Player.class);
return response.getBody();
}
tried to transform link using java.lang URI and URL. also just delete # or %23 from url. api doesnt get it

Getting "Invalid JSON payload received. Unexpected token.\ncode=4%2***\n^" error

So I am trying to make a HTTP request to get access token and refresh token using following java code.
String url = "https://oauth2.googleapis.com/token?";
Map<String, String> parameters = new HashMap<>();
parameters.put("code", "4%2******");
parameters.put("client_id", "*****");
parameters.put("client_secret", "*****");
parameters.put("redirect_uri", "http://localhost");
parameters.put("grant_type","authorization_code");
parameters.put("access_type","offline");
String form = parameters.keySet().stream()
.map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/json")
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
But using this code gives the following error,
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\ncode=4%2****\n^",
"status": "INVALID_ARGUMENT"
}
}
What is the mistake that I have done here and should rectify in order to get proper results?
You are sending application/x-www-form-urlencoded data format but according to the response message you should send json. Try to change definition of form:
String form = new ObjectMapper().writeValueAsString(parameters);

Java jersey client consumes JsonArray of jsonArray

I have a special kind of parsing JSON url :
[{"exchangeRates":[{"currencyISO":"AUD","currencyShortName":"dolar"}]}]
to do that i need to pass by a proxy and a jersey client :
URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
Client client = new Client(ch);
WebResource resource = client.resource("https://api.xxxx");
resource.type(MediaType.APPLICATION_JSON);
ExchangeRates[] responseMsg = resource.path("/openapi/xxxx").get(ExchangeRates[].class);
the response is :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.xxx.ExchangeRates out of START_ARRAY token at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#236cfcf; line: 1, column: 1]
ExchangeRates is a list of ExchangeRate object.
I can't find a way how to parse this json.Any recommandation ?

"null" value failing to serialize

I am using Jersey client to access rest service.
I am using JSONObject and setting a "null" literal in it. It fails while it is serialized.
Upon investigating, I found JSONNull.equals() method has this "null".equals(value) then it considers the value as JSONNull object.
And then, JSONNull#isEmpty() throws exceptions.
net.sf.json.JSONObject params = new net.sf.json.JSONObject();
params.put("PGHIDENTIFIE", "null");
And when serialized it throws:
Caused by: com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject["PGHIDENTIFIE"]->net.sf.json.JSONNull["empty"])
How can I serialize that "null" value inside JSONObject? Thanks!
DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
defaultClientConfig.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(defaultClientConfig);
WebResource webResource = client.resource(apiUrl);
ClientResponse response =
webResource.path(apiUrl).accept("application/json")
.type("application/json").post(ClientResponse.class, params);

Getting one field from response entity json

i need to connect to a rest service to get the user id by using a token.
List<Object> providers = new ArrayList<>();
providers.add(new JacksonJaxbJsonProvider());
client = WebClient.create(properties.getProperty(URL), providers);
client = client.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE);
client.path(PATH + token);
Response response = client.get();
The entity of response have this format:
{"message":"Token is valid","userId":1}
To get the userId, i have:
response.readEntity(AuthResponse.class).userId;
It is possible to take only the userId without creating an class with that format ? (without AuthResponse.class)
You can try to read your JSON as Map, for example: response.readEntity(Map.class).get("userId")
Please refer to this page for more information.

Categories