我正在构建我的 oauth2-protecet Web 服务和客户端。对于网络服务,我使用了 spring security 实现和 used this as example 。对于客户,我正在尝试 apache oltu 库。这是我的片段:
OAuthClientRequest request = OAuthClientRequest.tokenLocation
("http://localhost:8080/oauth/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId("clientapp")
.setClientSecret("123456")
.buildHeaderMessage();
OAuthAccessTokenResponse oAuthResponse = cli.accessToken(request);
System.out.println(oAuthResponse.getAccessToken());
它不起作用。虽然这
curl -X POST -vu clientapp:123456 --data "grant_type=client_credentials&client_secret=123456&client_id=clientapp" http://localhost:8080/oauth/token
工作得很好。这是 curl 请求:
POST /oauth/token HTTP/1.1
Authorization: Basic Y2xpZW50YXBwOjEyMzQ1Ng==
User-Agent: curl/7.35.0
Host: localhost:8080
Accept: */*
Content-Length: 70
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_secret=123456&client_id=clientapp
如您所见,我使用了curl 的基本身份验证并且它有效(即使建议的身份验证类型是承载)。
这是 oltu 数据包:
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer client_credentials123456clientapp
User-Agent: Java/1.8.0_51
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 4
null
我不确定承载授权是如何工作的,但这个数据包看起来完全错误。
我还尝试使用 buildBodyMessage()
和 buildQueryMessage()
而不是 this post 中建议的 buildHeaderessage()
,但它不是也不错。
最佳答案
这条线看起来不太健康:
Authorization: Bearer client_credentials123456clientapp
我用 Oltu 创建了一个测试服务器,基本上是一个 servlet:
OAuthResponse oauthResponse = OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(accessToken)
.setExpiresIn(Integer.toString(expires))
.setRefreshToken(refreshToken)
.buildJSONMessage();
response.setStatus(oauthResponse.getResponseStatus());
response.setContentType("application/json");
对于我得到的客户:
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("http://localhost:8083/OltuServer/token")
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId("clientapp")
.setClientSecret("123456")
.buildQueryMessage();
OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(request);
System.out.println(oAuthResponse.getAccessToken());
与您的代码的主要区别是 buildQueryMessage()。使用 buildHeaderMessage() 我在服务器上遇到异常
OAuthProblemException {error='invalid_request', description='Missing grant_type parameter value' ... }
但是我看到 Oltu 现在是 1.0.1 版本,而我一直在 1.0.0 版本上进行测试。该版本的行为可能有所不同。
关于java - OAuth2 oltu 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855176/