问题
I'm trying to retrieve a OAUTH2 token from our IDM server - I've tried several flavors of rudimentary examples, but all of them return a 200 status with no code included. I can do it with no trouble via postman, using a header of:
Content-Type application/x-www-form-urlencoded
... and sending the client_id, redirect_uri and code parameters. I get something back that looks like this:
{
"access_token": "abcd...",
"token_type": "bearer",
"expires_in": 3600
}
Here's the super rudimentary code intended to do no more than see if I can grab the token (at this point):
public class Service {
public String getToken() {
String client_id = "f2e8...";
String redirect_uri = "https://mysite/";
String code = "AAAAAA...";
form = new Form();
form.param("client_id", client_id);
form.param("code", code);
form.param("redirect_uri", redirect_uri);
JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder();
JerseyWebTarget jerseyWebTarget =
jerseyClientBuilder.build().target("https://token-source-site/");
Response response = jerseyWebTarget.request().post(Entity.form(form));
return response.toString();
}
}
But all I get back is:
InboundJaxrsResponse{context=ClientResponse{method=POST,
uri=https://token-source-site/, status=200, reason=OK}}
Any thoughts on what Postman might be doing that my code isn't?
回答1:
It's not going to show to the response body when you just call toString() on the Response. You need to extract the body from it by calling Response#readEntity.
But even trying to extract it to a String, you have the problem of still having to parse the string. Best thing to do is to create a POJO for the token response
public class AccessTokenResponse {
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("expires_in")
private long expiresIn;
// getters and setters
}
Then you can do
Response response = jerseyWebTarget.request().post(Entity.form(form));
return response.readEntity(AccessTokenResponse.class);
Make the method return AccessTokenResponse, so the client has access to the other properties also.
For this to work, you will need to have the Jackson provider dependency
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
来源:https://stackoverflow.com/questions/48554109/getting-the-oauth2-token