我的答案將基於奧爾圖。我將使用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