2011-10-14 3 views
1

현재 Google 문서 및 캘린더 API를 사용하는. NET WPF 응용 프로그램을 작성하고 있습니다. Tasks와 같은 최신 API 중 일부를 나중에 통합 할 계획이므로 OAuth 2.0을 준비 중에 시작하겠습니다. 나는 새로 고침과 액세스 토큰을 모두 가져 와서 저장할 수 있었고 현재 토큰이 만료 될 때 추가 액세스 토큰을 검색 할 수있는 로직을 구현했습니다. 그러나 나는 구글 docs에 문서를 업로드하는 데 많은 어려움을 겪고있다. GData 클라이언트 라이브러리는 OAuth 2.0을 기본적으로 지원하지 않으므로이 단계에서 DotNetOpenAuth에 의존하지 않으므로 새 클라이언트 라이브러리 (예 : 작업)로 이동하고 싶지 않습니다. 대신 OAuth2Authenticator를 구현하여 필요한 OAuth 2 헤더를 추가하고 이것을 GData ResumableUploader와 함께 사용하고 있습니다. ResumableUploader로 문서를 업로드하라는 요청을 보내려고하면 Token Invalid - Invalid AuthSub token이라는 메시지와 함께 401 Unauthorized 응답이 나타납니다.OAuth 2.0을 반환하는 .NET Google GData 문서 API

이 같은 전화 만들고있어 :

ResumableUploader ru = new ResumableUploader(512); 

Document entry = new Document(); 
entry.Title = documentName; 
entry.MediaSource = new MediaFileSource(localDocumentPath, "application/pdf"); 
entry.Type = Document.DocumentType.PDF; 

Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); 
AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri); 
link.Rel = ResumableUploader.CreateMediaRelation; 
entry.DocumentEntry.Links.Add(link); 

ru.Insert(new OAuth2Authenticator("MyApplicationName", "MyAccessToken"), entry.DocumentEntry); 

(피들러에서) 요청 결과 :

POST https://docs.google.com/feeds/upload/create-session/default/private/full 
HTTP/1.1 Authorization: OAuth sOmeTThing+SomThNig+etc== 
Slug: DOC_0108.pdf 
X-Upload-Content-Type: application/pdf 
X-Upload-Content-Length: 175268 
GData-Version: 3.0 
Host: docs.google.com 
Content-Type: application/atom+xml; charset=UTF-8 
Content-Length: 508 Connection: Keep-Alive 

<?xml version="1.0" encoding="utf-8"?> 
<entry xmlns="http://www.w3.org/2005/Atom" 
xmlns:gd="http://schemas.google.com/g/2005" 
xmlns:docs="http://schemas.google.com/docs/2007"> 
    <title type="text">DOC_0108.pdf</title> 
    <link href="https://docs.google.com/feeds/upload/create-session/default/private/full" 
    rel="http://schemas.google.com/g/2005#resumable-create-media" /> 
    <category term="http://schemas.google.com/docs/2007#pdf" 
    scheme="http://schemas.google.com/g/2005#kind" label="pdf" /> 
</entry> 

과 관련된를 401 응답 :

HTTP/1.1 401 Unauthorized 
Server: HTTP Upload Server Built on Sep 27 2011 04:44:57 (1317123897) 
WWW-Authenticate: AuthSub realm="http://www.google.com/accounts/AuthSubRequest" 
Content-Type: text/html; charset=UTF-8 
Content-Length: 38 
Date: Thu, 13 Oct 2011 08:45:11 GMT 
Pragma: no-cache 
Expires: Fri, 01 Jan 1990 00:00:00 GMT 
Cache-Control: no-cache, no-store, must-revalidate 

Token invalid - Invalid AuthSub token. 

나는 API와 OAuth 2.0 문서가 나뉘어져있는 것처럼 헤더에 'Authorization : OAuth'와 'Authorization : Bearer'둘 다 표시되었으며 토큰을 쿼리 문자열 (? access_token = 및? oauth_token =)로 추가하려고 시도했지만 그 모든 것들은 동일한 반응을줍니다.

Google API 및 OAuth 관련 질문, 블로그 게시물,이 호출을 수행 할 수있는 다양한 방법 (.NET GData API, REST 클라이언트 NuGet 패키지, 자체 구현 REST 클라이언트 구현 등)이 문제를 해결할 수는 없습니다.

도움이 될 것입니다.

답변

0

OAuth를 사용하여 문서를 만들고 만들 수 있습니다. 나는이 문서의 범위에 액세스 할 수 있도록 구글 인증하면, 나는 다음을 수행하십시오

// get the list of available google docs 
     RequestSettings settings = new RequestSettings(kApplicationName); 
     settings.AutoPaging = false; 
     if (settings != null) 
     { 
      DocumentsRequest request = new DocumentsRequest(settings); 
      request.Service.RequestFactory = GetGoogleOAuthFactory(); 
      Feed<Document> feed = request.GetEverything(); 

      List<Document> all = new List<Document>(feed.Entries); 

      // loop through the documents and add them from google 
      foreach (Document entry in all) 
      { 
       // first check to see whether the document has already been selected or not 
       bool found = model.Docs.Any(d => d.GoogleDocID == entry.ResourceId); 
       if (!found) 
       { 
        GoogleDocItem doc = new GoogleDocItem(); 
        doc.GoogleDocID = entry.ResourceId; 
        doc.ETag = entry.ETag; 

        doc.Url = entry.DocumentEntry.AlternateUri.Content; 
        doc.Title = entry.Title; 
        doc.DocType = entry.Type.ToString(); 
        doc.DocTypeID = entry.Type; 

        if (entry.ParentFolders.Count == 0) 
        { 
         // add the doc to the list 
         model.AvailableDocs.Add(doc); 

         // if the doc is a folder, get the children 
         if (doc.DocTypeID == Document.DocumentType.Folder) 
         { 
          AddAllChildrenToFolder(ref doc, entry, all); 
         } 
        } 
       } 
      } 
     } 

public GOAuthRequestFactory GetGoogleOAuthFactory() 
    { 
     // build the base parameters 
     OAuthParameters parameters = new OAuthParameters 
     { 
      ConsumerKey = kConsumerKey, 
      ConsumerSecret = kConsumerSecret 
     }; 

     // check to see if we have saved tokens and set 
     var tokens = (from a in context.GO_GoogleAuthorizeTokens select a); 
     if (tokens.Count() > 0) 
     { 
      GO_GoogleAuthorizeToken token = tokens.First(); 
      parameters.Token = token.Token; 
      parameters.TokenSecret = token.TokenSecret; 
     } 

     // now build the factory 
     return new GOAuthRequestFactory("anyname", kApplicationName, parameters); 
    } 

나는 여기에 내 승인 샘플을 게시 : .net - Google/OAuth 2 - Automatic logon을. DocumentsRequest는 Google의 .NET 바이너리에 있습니다. 아직 새 문서를 만들지 않았지만 비슷한 클래스를 사용하여 일정 항목을 만듭니다.