使用GData访问Google文档

时间:2011-09-19 12:36:12

标签: c# asp.net oauth gdata-api google-docs

工作平台:ASP.NET 4.0 C#(框架不可知)

Google GData是我的依赖

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;

我有两页Auth和List。

Auth重定向到Google服务器

public ActionResult Auth()
{
    var target = Request.Url.ToString().ToLowerInvariant().Replace("auth", "list");
    var scope = "https://docs.google.com/feeds/";
    bool secure = false, session = true;

    var authSubUrl = AuthSubUtil.getRequestUrl(target, scope, secure, session);
    return new RedirectResult(authSubUrl);
}

现在,如果身份验证成功,它就会到达列表页面。

public ActionResult List()
{
    if (Request.QueryString["token"] != null)
    {
        String singleUseToken = Request.QueryString["token"];

        string consumerKey = "www.blahblah.net";
        string consumerSecret = "my_key";
        string sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null).ToString(); 

        var authFactory = new GOAuthRequestFactory("writely", "qwd-asd-01");
        authFactory.Token = sessionToken;
        authFactory.ConsumerKey = consumerKey;
        authFactory.ConsumerSecret = consumerSecret;
        //authFactory.TokenSecret = "";
        try
        {
            var service = new DocumentsService(authFactory.ApplicationName) { RequestFactory = authFactory };

            var query = new DocumentsListQuery();
            query.Title = "project";

            var feed = service.Query(query);
            var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
            return View(result);
        }
        catch (GDataRequestException gdre)
        {
            throw;
        }
    }
}

这行var feed = service.Query(query);失败,错误

  

执行请求失败:https://docs.google.com/feeds/default/private/full?title=project

catch块上收到的HttpStatusCodeHttpStatusCode.Unauthorized

这段代码有什么问题?我需要获得TokenSecret吗?如果是这样的话?

2 个答案:

答案 0 :(得分:1)

您需要从Google请求令牌并使用它来初始化您的DocumentsService实例。

以下是使用Google的ContactsService的示例。对于DocumentsService,它应该是相同的。

Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("your_email_address_here@gmail.com", "yourpassword");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);

但正如您所说,您使用的是AuthSub。我跳得太快了。

我看到您正在请求会话令牌。根据API的文档,您必须使用会话令牌通过将令牌放在Authorization标头中来验证对服务的请求。设置会话令牌后,您可以使用Google Data API客户端库。

以下是关于如何将AuthSub与.NET客户端库一起使用的完整示例(由Google提供):

http://code.google.com/intl/nl-NL/apis/gdata/articles/authsub_dotnet.html

让我举一个缩短的例子:

GAuthSubRequestFactory authFactory = 
    new GAuthSubRequestFactory("cl", "TesterApp");
authFactory.Token = (String) Session["token"];
CalendarService service = new CalendarService(authFactory.ApplicationName);
service.RequestFactory = authFactory;

EventQuery query = new EventQuery();

query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");

EventFeed calFeed = service.Query(query);
foreach (Google.GData.Calendar.EventEntry entry in calFeed.Entries)
{
    //...
}

如果我正确地看到你的示例代码非常遵循相同的步骤,除了你为AuthFactory设置了ConsumerKey和ConsumerSecret,这在Google的例子中没有完成。

答案 1 :(得分:1)

使用3-legged OAuth in the Google Data Protocol Client Libraries

示例代码

string CONSUMER_KEY = "www.bherila.net";
string CONSUMER_SECRET = "RpKF7ykWt8C6At74TR4_wyIb";
string APPLICATION_NAME = "bwh-wssearch-01";

string SCOPE = "https://docs.google.com/feeds/";

public ActionResult Auth()
{
    string callbackURL = String.Format("{0}{1}", Request.Url.ToString(), "List");
    OAuthParameters parameters = new OAuthParameters()
    {
        ConsumerKey = CONSUMER_KEY,
        ConsumerSecret = CONSUMER_SECRET,
        Scope = SCOPE,
        Callback = callbackURL,
        SignatureMethod = "HMAC-SHA1"
    };

    OAuthUtil.GetUnauthorizedRequestToken(parameters);
    string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
    Session["parameters"] = parameters;
    ViewBag.AuthUrl = authorizationUrl;
    return View();
}

public ActionResult List()
{
    if (Session["parameters"] != null)
    {
        OAuthParameters parameters = Session["parameters"] as OAuthParameters;
        OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);

        try
        {
            OAuthUtil.GetAccessToken(parameters);

            GOAuthRequestFactory authFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);

            var service = new DocumentsService(authFactory.ApplicationName);
            service.RequestFactory = authFactory;

            var query = new DocumentsListQuery();
            //query.Title = "recipe";

            var feed = service.Query(query);
            var docs = new List<string>();
            foreach (DocumentEntry entry in feed.Entries)
            {
                docs.Add(entry.Title.Text);
            }
            //var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
            return View(docs);
        }
        catch (GDataRequestException gdre)
        {
            HttpWebResponse response = (HttpWebResponse)gdre.Response;

            //bad auth token, clear session and refresh the page
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                Session.Clear();
                Response.Write(gdre.Message);
            }
            else
            {
                Response.Write("Error processing request: " + gdre.ToString());
            }
            throw;
        }
    }
    else
    {
        return RedirectToAction("Index");
    }
}

This 2-legged sample从来没有为我的谷歌文档工作。