2011-04-28 4 views
1

나는 example web.py app에 REST 서비스 + OAuth2를 제공하고 있습니다. 파이썬에서, 클라이언트 응용 프로그램 등이 같은 이름으로 서명, OAuth2를 소비자, 요청을 생성하는 과정을 거친 (의사 코드 참조를 완료하지) :Java에서 두 개의 다리가있는 OAuth2 예제?

import json 
import time 
import oauth2 
import urllib2 

# Set up the POST variables 
method = 'POST' 
url = 'https://localhost/service/rest' 
parameters = { 
    'username' : username, 
    'password' : password 
} 

# Generate our Consumer object 
consumer = oauth2.Consumer(key = KEY, secret = SECRET) 

# Add additional parameters required by OAuth 
parameters['oauth_version']  = "1.0" 
parameters['oauth_nonce']  = oauth2.generate_nonce() 
parameters['oauth_timestamp'] = int(time.time()) 
parameters['oauth_consumer_key'] = consumer.key 

# Generate and sign the request 
oauth = oauth2.Request(method = method, url = url, parameters = parameters) 
signature_method = oauth2.SignatureMethod_HMAC_SHA1() 
oauth.sign_request(signature_method, consumer, None) 

# Shoot it off to the webserver 
req = urllib2.Request(BASE_URL, oauth.to_postdata()) 
result = urllib2.urlopen(req).read() 
json_result = json.loads(result) 
print json_result 

TADA을! 그것은 챔피언처럼 작동합니다. 자바에서 똑같은 일을하려고합니다. 안드로이드에서 그렇습니다.하지만이 시점에서는 무엇이든 할 것입니다. 필자가 본 모든 사례는 3-legged auth를 사용하여 공개 OAuth2 API에 중점을 두거나 웹 서비스 용 서버 측 구성에 초점을 맞 춥니 다.

누군가 나를 불쌍히 여겨 Java에서 똑같이 간단한 예제 인 BasicHttpContext, DefaultHttpClient 및 friends를 사용할 수 있습니까?

는 자신의 질문에 대답 나중에

그것은 아마도 간주 나쁜 양식을 편집 할 수 있지만 여기에 내가 부탁 한 일을하는 방법입니다. 두 발의 oauth는 실제로 OAuth v1.0 기능이므로 반포 된 oauth.signpost 라이브러리는 쉽게 수행 할 수 있습니다. 최근에 유지 관리 된 joauth 라이브러리를 사용하려고 시도했지만 원하는 비트 만 수행하는 좋은 예제를 찾을 수 없었습니다. 이 코드는 실제로 내 코드에서 3 ~ 4 개의 서로 다른 Java 파일로 분산되어 있지만이 의사 코드 예제에서는 모두 함께 사용했습니다. 당신은 백엔드에 서명을 확인하는 경우

import ... 
import oauth.signpost.OAuthConsumer; 
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; 
import oauth.signpost.exception.OAuthCommunicationException; 
import oauth.signpost.exception.OAuthExpectationFailedException; 
import oauth.signpost.exception.OAuthMessageSignerException; 

public class RestClient { 

    private OAuthConsumer oauth_consumer = null; 
    private DefaultHttpClient http_client; 
    private static final String consumer_key = "something"; 
    private static final String consumer_secret = "something_else"; 

    public RestClient(Context context) { 
    // Instantiate our custom http client with our trusted key 
    this.http_client = new DefaultHttpClient(); 
    // Instantiate an oauth_consumer 
    this.oauth_consumer = new CommonsHttpOAuthConsumer(consumer_key, consumer_secret); 
    } 

    public POST(String url, Map params) { 
    // Initialize our post request 
    HttpPost httppost = new HttpPost(url); 
    httppost.setHeader("Accept", "application/json"); 
    httppost.setHeader("Content-type", "application/x-www-form-urlencoded"); 

    // This iterates through the parameters and stores them for use 
    List<NameValuePair> name_value_pairs = new ArrayList<NameValuePair>(2); 
    Iterator iter = params.entrySet().iterator(); 
    while (iter.hasNext()) { 
     Map.Entry pairs = (Map.Entry)iter.next(); 
     name_value_pairs.add(
     new BasicNameValuePair((String)pairs.getKey(), (String)pairs.getValue()) 
    ); 
    } 

    try { 
     // Put our parameters in our Post 
     httppost.setEntity(new UrlEncodedFormEntity(name_value_pairs)); 
     // sign our request 
     this.oauth_consumer.sign(httppost); 
     // Yoiks, and away! 
     HttpResponse response = http_client.execute(httppost); 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
     InputStream instream = entity.getContent(); 
     JSONObject json = new JSONObject(convertStreamToString(instream)); 
     // Closing the input stream will trigger connection release 
     instream.close(); 
     return json; 
     } catch (aBunchOfShit e) { 
     e.printStackTrace(); 
     } 
    } 
    return null; 
    } 
} 

, 당신이 요청에서 전달 모든 매개 변수를 포함해야합니다. 나는 "잘못된 서명. 예상 된 서명 기본 문자열 POST & ..."을보고 앉아서 System.setProperty ("debug", "1");을 설정하는 방법을 알기 전까지 한 시간 동안 오류가 발생했습니다. Java 측에서 원래의 기본 문자열을 보았습니다. 지금은 충분하지만 여전히 유지 관리되는 라이브러리에서 작동하는 방식을보고 싶습니다.

+0

'new DefaultHttpClient'의 인수로'context'를 사용한 방법을 이해하지 못합니다. DefaultHttpClient가 HttpParams를 가져 가지 않습니까? – LuxuryMode

+0

사용한 코드는 OAuth 1.0a 인증을 따르지만 제목은 2-Legged OAuth를 묻습니다. –

+0

@LuxuryMode는 오타였습니다. 혼란을 드려 죄송합니다! – DaGoodBoy

답변

1

joauth에 대해 언급 한 바 있으므로 JOAuth를 사용하여 OAuth 1 인증을 허용하려면 documentation을 작성했습니다.

이 정보가 도움이되기를 바랍니다.

관련 문제