2014-11-16 4 views
5

documentation에 주어진 샘플 인증 요청 (또는 인증이 필요한 Etsy의 API가있는 것)을 수행하려고합니다. 내가 얻는 응답은 "oauth_problem = token_rejected"입니다.Etsy oauth authentication C# RestSharp

나는 과 함께 benSharper과 연결된 this SO answer을 사용했습니다.

나는 thisthis 등을 살펴 보았습니다. 그들 중 하나는 https://sandbox.https://openapi.etsy.com/v2을 사용했고 그 시도에서 예외는 "기본 연결이 닫혔습니다 : SSL/TLS 보안 채널에 대한 트러스트 관계를 설정할 수 없습니다." 내 서버 (https)에 배포했지만 여전히 동일한 응답입니다.

그냥 작동하지 않는 것 같습니다. 내가 뭘 놓치고 있니? 어떤 도움을 크게 감상 할 수

public class AuthorizedRequestHelper 
    { 
     string baseUrl = "https://openapi.etsy.com/v2"; 
     string relativePath = "/oauth/scopes"; 
     string oauth_consumer_key = "xxx"; 
     string consumerSecret = "xxx"; 
     string oauth_token = "xxx"; 
     string oauth_token_secret = "xxx"; 

     public void test() 
     { 
      var restClient = new RestClient(baseUrl); 
      OAuthBase oAuth = new OAuthBase(); 

      string nonce = oAuth.GenerateNonce(); 
      string timeStamp = oAuth.GenerateTimeStamp(); 
      string normalizedUrl; 
      string normalizedRequestParameters; 

      string sig = oAuth.GenerateSignature(new Uri(baseUrl + relativePath), oauth_consumer_key, consumerSecret, oauth_token, oauth_token_secret, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters); 


      var request = new RestRequest(relativePath); 
      request.Resource = string.Format(relativePath); 
      request.Method = Method.GET; 

      request.AddParameter("oauth_consumer_key", oauth_consumer_key); 
      request.AddParameter("oauth_token", oauth_token); 
      request.AddParameter("oauth_nonce", nonce); 
      request.AddParameter("oauth_timestamp", timeStamp); 
      request.AddParameter("oauth_signature_method", "HMAC-SHA1"); 
      request.AddParameter("oauth_version", "1.0"); 
      request.AddParameter("oauth_signature", sig); 

      IRestResponse irestResponse = restClient.Execute(request); 
      var content = irestResponse.Content; 
      // content = oauth_problem=token_rejected 
     } 
    } 

:

여기 내 코드입니다.

답변

9

제가 누락 된 부분을 파악했습니다. 보호 된 리소스에 액세스하는 데 필요한 영구적 인 토큰 인 Obtaining Token Credentials이 누락되었습니다.

OAuth, RestSharp 및 Etsy의 구현을 한 번에 해결하는 데 어려움이있었습니다. OAuthBase는 필요 없지만 RestSharp가 처리합니다.

RestSharp로 OAuth 호출을 할 때 appKeysharedSecretconsumerKeyconsumerSecret이됩니다.

여기서 일하고 코드 : (콜백)

/// <summary> 
    /// RestSharp documentation: https://github.com/restsharp/RestSharp/wiki 
    /// </summary> 
    public class Etsy_portal 
    { 
     Uri BASE_URL = new Uri("https://openapi.etsy.com/v2/"); 

     string appKey; 
     string sharedSecret; 
     RestClient restClient; 

     private string[] _permissions_array; 
     public string Permissions 
     { 
      get { return string.Join(" ", _permissions_array); } 
     } 

     public Etsy_portal(string appKey_, string sharedSecret_) 
     { 
      appKey = appKey_; 
      sharedSecret = sharedSecret_; 

      restClient = new RestClient(BASE_URL); 

      //todo move permissions to Web.config 
      _permissions_array = new string[] { "listings_r", "listings_w", "listings_d", "shops_rw" }; 
     } 

     public string GetConfirmUrl(out string oauth_token, out string oauth_token_secret, string callbackUrl_ = null) 
     { 
      restClient.Authenticator = OAuth1Authenticator.ForRequestToken(appKey, sharedSecret, callbackUrl_ ?? "oob"); 

      RestRequest restRequest = new RestRequest("oauth/request_token", Method.POST); 

      restRequest.AddParameter("scope", Permissions); 

      IRestResponse response = restClient.Execute(restRequest); 

      if (response.StatusCode != System.Net.HttpStatusCode.OK) 
      { 
       oauth_token = null; 
       oauth_token_secret = null; 
       return null; 
      } 

      NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(response.Content); 

      oauth_token = queryString["oauth_token"]; 
      oauth_token_secret = queryString["oauth_token_secret"]; 

      return queryString["login_url"]; 
     } 

     public void ObtainTokenCredentials(string oauth_token_temp_, string oauth_token_secret_temp_, string oauth_verifier_, out string permanent_oauth_token_, out string permanent_oauth_token_secret_) 
     { 
      //consumerKey is the appKey you got when you registered your app, same for sharedSecret 
      restClient.Authenticator = OAuth1Authenticator.ForAccessToken(appKey, sharedSecret, oauth_token_temp_, oauth_token_secret_temp_, oauth_verifier_); 

      RestRequest restRequest = new RestRequest("oauth/access_token", Method.GET); 
      IRestResponse irestResponse = restClient.Execute(restRequest); 

      NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(irestResponse.Content); 

      permanent_oauth_token_ = queryString["oauth_token"]; 
      permanent_oauth_token_secret_ = queryString["oauth_token_secret"]; 
     } 

     public string GetScopes(string accessToken_, string accessTokenSecret_) 
     { 
      restClient.Authenticator = OAuth1Authenticator.ForProtectedResource(appKey, sharedSecret, accessToken_, accessTokenSecret_); 

      RestRequest restRequest = new RestRequest("oauth/scopes", Method.GET); 

      IRestResponse irestResponse = restClient.Execute(restRequest); 

      return irestResponse.Content; 
     } 
    } 

의사 코드 :

  1. Etsy_portal 객체
  2. 에게 전화 GetConfirmUrl를 구축 콜백 URL을 제공합니다. 콜백에는 두 개의 쿼리 매개 변수 oauth_tokenoauth_verifier이 있습니다. 다음은 콜백 함수 서명의 예는 다음과 같습니다

    [HttpGet] 공공 ActionResult EtsyCallback (문자열의 oauth_token, 문자열 oauth_verifier) ​​

  3. 저장 반환 나중에 검색을위한지도 구조에서 토큰 비밀.

  4. GetConfirmUrl으로 전화하여 확인 된 URL을 방문하십시오.
  5. 콜백 함수에서 위의 예에서 첫 번째 인수 인 제공된 토큰을 사용하여 3 단계에서 저장된 암호를 찾습니다.
  6. 검증 자 (위의 예에서 콜백 함수의 두 번째 인수) , 토큰 및 비밀은 ObtainTokenCredentials으로 전화하여 영구 토큰 및 비밀을 얻습니다.
  7. 영구 토큰과 암호를 저장하면 1-4 단계에서 얻은 확인 프로그램, 임시 토큰 및 임시 암호를 삭제할 수 있습니다.
+0

데스크톱 앱에서이 클래스를 사용하는 방법은 무엇입니까? – Volatil3

+0

클래스 라이브러리에 넣어서 웹 앱이나 데스크톱 앱에서 사용할 수 있습니다. 물론 적절한 참조를 추가해야합니다. –

+0

"OAuthBase가 필요하지 않습니다. RestSharp가 처리합니다." restsharp를 사용하여 서명 된 요청에 대한 OAuth 서명을 만들 수 있습니까 ?? @MichaelTranchida –