Here is my problem: when I try to call this method, I got this error
InboundJaxrsResponse{
context=ClientResponse{method=POST,
uri=http://localhost:9001/oauth/token, status=401,
reason=Unauthorized}}
public String getToken() {
String grant_type ="client_credentials";
String client_id = "abcd";
String client_secret = "mpoo";
Form form = new Form();
form.param("grant_type",grant_type);
form.param("client_id",client_id);
form.param("client_secret",client_secret);
JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder();
JerseyWebTarget jerseyWebTarget =
jerseyClientBuilder.build().target("http://localhost:9001/oauth/token");
Response response = jerseyWebTarget.request().post(Entity.form(form));
return response.toString();
}
Any Answer?
That's not the correct way to send the token request. Look at the RFC for client_credentials grant type. The correct format for the request is as follows:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
So only the grant_type
should be a part of the Form
body. The client_id
and client_secret
should be Base64 encoded and used for Basic Authentication:
String credentials = client_id + ":" + client_secret;
String base64 = Base64.getEncoder().encode(credentials.getBytes(StandardCharsets.UTF_8));
Response res = jerseyWebTarget.request()
.header(HttpHeaders.AUTHORIZATION, "Basic " + base64)
.post(Entity.form(form));