Unable to get token using API session token in Spring Boot

Hello Everyone,

I am trying to connect “http://localhost:3000/api/session” to get token but I always get an Error saying

Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{“errors”:{“username”:“value must be a non-blank string.”}}]

I tried multiple ways of adding username, password in the request but it doesnt recognise it. Below are the different options I tried :

Option 1 : Adding credentials as String

String request = “{“username”: “username”, “password”: “password”}”;

Option 2 : Adding the credentials to JSONObject

JSONObject request = new JSONObject();
request.put(“username”, “username”);
request.put(“password”, “password”);

Option 3 : Adding the credentials to Map

MultiValueMap<String, String> request= new LinkedMultiValueMap<String, String>();
request.add(“username”, “username”);
request.add(“password”, “password”);

Option 4: Adding crdentials to setBasicAuth() method

tokenHeaders.setBasicAuth(“username”, “password”);

Here is the actual code :

RestTemplate restTokenTemplate = new RestTemplate();
final String tokenUrl = “http://localhost:3000/api/session”;
URI tokenUri = new URI(tokenUrl);
HttpHeaders tokenHeaders = new HttpHeaders();
tokenHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity tokenEntity = new HttpEntity(request, tokenHeaders); // When option 1 or 2 or 3 is used at a time
ResponseEntity token = restTokenTemplate.exchange(tokenUri, HttpMethod.POST, tokenEntity, String.class);
System.out.println(token.getBody());
return token.getBody().toString();

@roshanyadav, try adding the credentials in the body of your request it should work. Atleast, it worked for me.

Hope that helps!

1 Like

Thank you for your response.
Can you please help posting code snippet for this. Becuase I am using RestTemplate to exchange and get the token and I didnt really find option to post body inthe HTTPrequest.

Here is the code I’m using :

RestTemplate restTokenTemplate = new RestTemplate();
final String tokenUrl = “http://localhost:3000/api/session”;
URI tokenUri = new URI(tokenUrl);
HttpHeaders tokenHeaders = new HttpHeaders();
tokenHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity tokenEntity = new HttpEntity(request, tokenHeaders); // When option 1 or 2 or 3 is used at a time
ResponseEntity token = restTokenTemplate.exchange(tokenUri, HttpMethod.POST, tokenEntity, String.class);
System.out.println(token.getBody());
return token.getBody().toString();

Found the solution :

HttpHeaders tokenHeaders = new HttpHeaders();
tokenHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
Map<String, Object> parametersMap = new HashMap<String, Object>();
parametersMap.put(“username”, metabaseUname);
parametersMap.put(“password”, metabasePwd);
// build the request
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(parametersMap, tokenHeaders);