How to use confidential client in keycloak?

I have OpenID public-type client that is linked to user. I can login into that user and get grops in access in token.

     HttpHeaders headers = new HttpHeaders();
     headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
     headers.put("grant_type", List.of("password"));
     headers.put("client_id", List.of("client-id"));
     headers.put("username", List.of("username"));
     headers.put("password", List.of("password"));
     headers.put("scope", List.of("openid"));
     String reponse = new RestTemplate()
       .postForObject("https://domain/auth/realms/r/protocol/openid-connect/token", headers, String.class);

But I get token in the same way for 'confidential' type client linked to user. Getting error 401. So, how can I authenticate for confidential type?


Solution 1:

You need to send also client secret for the confidential client -client_secret parameter. So in your case:

headers.put("client_secret", List.of("client_secret"));

Note: You can find client secret value, in the Keycloak client configuration Credentials section - it depends on used Client Authenticator, so it can be even more complicated.

Solution 2:

You're missing to send the client_secret in your request.

Confidential clients are required to provide a client secret when they exchange the temporary codes for tokens. Public clients are not required to provide this client secret.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.put("grant_type", List.of("password"));
headers.put("client_id", List.of("client-id"));
headers.put("client_secret", List.of("client-secret"));
headers.put("username", List.of("username"));
headers.put("password", List.of("password"));
headers.put("scope", List.of("openid"));
String reponse = new RestTemplate()
   .postForObject("https://domain/auth/realms/r/protocol/openid-connect/token", headers, String.class);