问题
I tried to implement an OAuth client using OAuthClientRequest in Apache Oltu. And it seems to be that it is sending client credentials in the message body not in the Basic Auth headers according to the spec. I am not sure, I may have missed some thing in the code.
Code
OAuthClientRequest.tokenLocation("http://localhost:8081/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(clientKey)
.setClientSecret(clientSecret)
.buildBodyMessage();
Request
POST /token HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cache-Control: no-cache Pragma: no-cache User-Agent: Java/1.6.0_29 Host: 127.0.0.1:8081 Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2 Connection: keep-alive Content-Length: 127
client_secret=f921854d-f70b-4180-9fdd-3a55032103cc&grant_type=client_credentials&client_id=3f3b4092-7576-4b26-8135-980db7864c2
回答1:
You might want to change buildBodyMessage()
with buildQueryMessage()
回答2:
The OAuth2 Bearer Token specification defines three methods of sending bearer access tokens:
- Authorization Request Header Field
- Form-Encoded Body Parameter
- URI Query Parameter
The method buildBodyMessage()
will create a request with a Form-Encoded Body Parameter. You need to use buildHeaderMessage()
instead, which is also the recommended method by the specification.
回答3:
Recently, I've trying to find a OAuth2 java library to get "client_credential" type of accesstoken. And below is what I have for Apache Oltu, and it seems that it is working.
@Test
public void getAccessTokenViaApacheOltuOAuthClient() {
try{
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthClientRequest request =
OAuthClientRequest.tokenLocation(TOKEN_REQUEST_URL)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setScope(StringUtils.join(TEST_SCOPES, " ")) //if you have scope
.buildBodyMessage();
String token =
client.accessToken(request, "POST", OAuthJSONAccessTokenResponse.class)
.getAccessToken();
System.out.println(token);
assertTrue( token != null);
} catch (Exception e) {
e.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/20216786/client-credential-grant-type-is-not-properly-sent-with-apache-oltu-client-librar