.NET谷歌文档的GData API使用OAuth 2.0返回401文档、GData、NET、API

2023-09-06 19:02:40 作者:sensitive(敏感)

我目前正在写一个使用谷歌Docs和日历API的.NET WPF应用程序。我正打算整合一些新的API,如任务,在后一阶段,所以我要开始在preparation使用OAuth 2.0现在。我已经能够获得并同时存储刷新和访问令牌,我已经实现了一些逻辑来获取进一步的访问令牌在当前那些到期。但是我有很多麻烦上传文件到Google文档。看来,GData的客户端库本身不支持的OAuth 2.0,我不想要移动到较新​​的客户端库(如任务),因为我不想在DotNetOpenAuth的依赖在这个阶段。相反,我已经实现了我自己的OAuth2Authenticator它增加了所需的OAuth 2头,我用这个用的GData ResumableUploader。当我尝试将请求发送到上传文档与ResumableUploader我得到的消息令牌无效401未经授权的响应 - 无效的AuthSub令牌。

I'm currently writing a .NET WPF application that uses the Google Docs and Calendar APIs. I'm planning to integrate some of the newer APIs, like Tasks, at a later stage so I want to start using OAuth 2.0 now in preparation. I've been able to obtain and store both a refresh and access token and I've implemented some logic to retrieve further access tokens when the current ones expire. However I'm having a lot of trouble uploading a document to google docs. It seems that the GData client libraries don't natively support OAuth 2.0 and I don't want to move to the newer client libraries (e.g. for Tasks) because I don't want a dependency on DotNetOpenAuth at this stage. Instead I've implemented my own OAuth2Authenticator which adds the required OAuth 2 header and I'm using this with the GData ResumableUploader. When I try to send the request to upload a document with the ResumableUploader I get a 401 Unauthorised response with the message Token Invalid - Invalid AuthSub token.

我做这样的电话:

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.

我都试过授权:OAuth的'和?'授权:承载的标题,作为API和OAuth的2.0文件似乎分开,我也试着追加令牌作为查询字符串(access_token =和?oauth_token =),但所有这些事情给了同样的答复。

I've tried both 'Authorization: OAuth' and 'Authorization: Bearer' in the headers, as the API and OAuth 2.0 documentation seems divided, and I've also tried appending the token as a query string (?access_token= and ?oauth_token=) but all of those things give the same response.

我已经通过所有的谷歌API和OAuth的问题,博客,文档可以找我,并试图执行此调用(多个实现与.NET的GData的API,REST客户端的NuGet包,我自己休息的多种方式客户端实现,等等),我不能让过去这个问题。

I've been through all the Google API and OAuth questions, blog posts, documentation I can find and tried numerous ways of performing this call (multiple implementations with the .NET GData APIs, a REST client NuGet package, my own REST client implementation, etc.) and I can't get past this issue.

任何帮助将是最AP preciated。

Any help will be most appreciated.

推荐答案

我能够获取和创建与OAuth的文档。有一次,我已经验证与谷歌可以访问文档的范围,我执行以下操作:

I am able to get and create documents with OAuth. Once I've authenticated with Google to have access to the docs scope, I do the following:

// 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 - 谷歌/ OAuth的2 - 自动登录。该DocumentsRequest是从谷歌在.NET二进制文件。虽然我还没有创建一个新的文档与此的是,我使用相似的类来创建日历项目。

I posted my authorization sample over here: .net - Google / OAuth 2 - Automatic logon. The DocumentsRequest is from the .NET binaries from Google. While I haven't created a new document with this yet, I do use similar classes to create Calendar items.