我的答案将基于奥尔图。我将使用CLIENT_CREDENTIALS认证。
获取令牌应该是这样的:
// We initialize a client
OAuthClient lOAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse lOAuthResponse;
// We are creating a request that's already formatted following the Oauth specs
OAuthClientRequest lRequest = OAuthClientRequest
.tokenLocation(TOKEN_SERVER_URI)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setScope("admin")
.buildBodyMessage();
//This will submit the request
String code = lOAuthClient.accessToken(lRequest, OAuthJSONAccessTokenResponse.class).getAccessToken();
System.out.println("Token obtained:" + token);
现在我们可以用我们的令牌获得我们的ressource:
HttpURLConnection resourceConn = (HttpURLConnection) (new URL(RESSOURCE_SERVER_URI).openConnection());
resourceConn.addRequestProperty("Authorization", "Bearer " + token);
InputStream resource = resourceConn.getInputStream();
// Do whatever you want to do with the contents of resource at this point.
BufferedReader r = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
String line = null;
while ((line = r.readLine()) != null)
System.out.println(line);
你可以从春天例子模式 – haseeb
我会后你的解释,但首先我需要知道:你是否理解OAuth的功能及其许多部分(客户端,用户,资源服务器等)? – Nathan
@ user3252187我发布了一个基于[oltu示例](https://cwiki.apache.org/confluence/display/OLTU/OAuth+2.0+Client+Quickstart)的测试客户端的样子,以及我自己的代码(主要来自互联网)。 – Nathan