使用服务帐户访问Google通讯录json c#

时间:2017-07-24 16:08:53

标签: c# asp.net json oauth-2.0 googlecontactsapi

我正在尝试使用OAuth 2.0 for ASP.net MVC应用程序中的服务器到服务器应用程序访问我的Google通讯录,但我在尝试检索令牌时遇到了一些麻烦。 “test-470272c3a5fa.json”是我从谷歌api控制台下载的文件,目前在我的桌面上。有什么想法吗?

这是我的代码:

public class GoogleContactsApiInterface
{
    public GoogleContactsApiInterface()
    {
        ServiceAccountCredential serviceAccountCredential;
        string[] scopes = { "https://www.google.com/m8/feeds/" };
        string keyPath = "C:\\Users\\55122545\\Desktop\\test-470272c3a5fa.json";

        using (var stream = new FileStream(keyPath, FileMode.Open, FileAccess.Read))
        {
            serviceAccountCredential =  GoogleCredential.FromStream(stream)
                                                        .CreateScoped(scopes)
                                                        .UnderlyingCredential as ServiceAccountCredential;

            OAuth2Parameters parameters = new OAuth2Parameters();
            parameters.AccessToken  = serviceAccountCredential.Token.AccessToken;
            parameters.RefreshToken = serviceAccountCredential.Token.RefreshToken;

            RequestSettings rs = new RequestSettings("testApp", parameters);
            rs.AutoPaging = true;

            ContactsRequest cr = new ContactsRequest(rs);

            Feed<Contact> f = cr.GetContacts();

            foreach (Contact c in f.Entries)
            {
                //do something
            }

        }
    }
}

0 个答案:

没有答案