How to authenticate in REST from Java code

https://docs.jmix.io/jmix/rest/getting-started.html

Hi, I am trying to send a request from java software to the rest api. I have tried the commands of jmix rest api as per documentation and have a few doubts…

curl -X POST http://localhost:8080/oauth/token \
   --basic --user client:secret \
   -H "Content-Type: application/x-www-form-urlencoded" \
   -d "grant_type=password&username=admin&password=admin"

In the above example, what is’–basic’, ‘–user’ and ‘client:secret’.

Meaning if i want to send a request from a software, where will i put this in the code ?

Hi Vikrant,

These are arguments of the curl command.
See more detailed explanation of the authentication process in the Authentication section.

In Java, you can authenticate in Jmix REST API using HttpClient as follows:

public void test() {
    authenticate("client", "secret", "admin", "admin");
}

private void authenticate(String client, String secret, String username, String password) {
    HttpClient httpClient = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:8080/oauth/token"))
            .header("Authorization", getBasicAuthHeader(client, secret))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .POST(HttpRequest.BodyPublishers.ofString(getAuthRequestBody(username, password)))
            .build();
    try {
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == HttpStatus.OK.value()) {
            String responseText = response.body();
            System.out.println("Response: " + responseText);
            // Using Jackson to convert JSON responce to a map:
            Map<String, Object> map = new ObjectMapper().readValue(responseText, Map.class);
            String accessToken = (String) map.get("access_token");
            System.out.println("Access token: " + accessToken);
        } else {
            System.out.println("Error: " + response.statusCode());
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

private String getBasicAuthHeader(String client, String secret) {
    String str = client + ":" + secret;
    return "Basic " + Base64.getEncoder().encodeToString(str.getBytes());
}

private String getAuthRequestBody(String username, String password) {
    return "grant_type=password&username=" + username + "&password=" + password;
}
1 Like

Thanks. It worked

hi Konstantin, your code example helped me a lot. I receive the system notification: “o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token”

Can you give me a hint what the cause of this could be? Thx in advance.

best regards,

Michael

Hi Michael,

The message says that the access token which you are sending in the Authorization header (see Making API Requests) is not found. Are you sure you are sending the token received through the /oauth/token request?

thank you Konstantin

My issue was solved with your answer for me in an other thread. Sorry for the confusion.

greetings,

Michael