如何使用访问令牌和刷新令牌从google api访问用户日历列表和事件

时间:2016-07-20 20:46:56

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

我已经使用oAuth2从谷歌api获得了用户访问令牌。现在我想使用此令牌来获取用户事件/日历。我尝试过以下代码,但它无效。

有人可以帮我这个。 感谢

    var urlBuilder = new System.Text.StringBuilder();

    urlBuilder.Append("https://");
    urlBuilder.Append("www.googleapis.com");
    urlBuilder.Append("/calendar/v3/users/me/calendarList");
    urlBuilder.Append("?minAccessRole=reader");

    var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString()) as HttpWebRequest;

    httpWebRequest.CookieContainer = new CookieContainer();
    httpWebRequest.Headers["Authorization"] string.Format("Bearer {0}", data.access_token);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream eventResponseStream = response.GetResponseStream();
    StreamReader eventResponseStreamReader = new StreamReader(responseStream);
    string eventsStr = eventResponseStreamReader.ReadToEnd();

2 个答案:

答案 0 :(得分:2)

我找到了使用Google.Apis.Calendar.v3的解决方案,我在这里发布,所以可以帮助其他人。以下是当您拥有用户的刷新令牌时获取事件列表的代码:

首先使用刷新令牌获取新的访问令牌:

string postString = "client_id=yourclientid";
postString += "&client_secret=youclientsecret&refresh_token=userrefreshtoken";
postString += "&grant_type=refresh_token";
string url = "https://www.googleapis.com/oauth2/v4/token";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;

    request.ContentLength = bytes.Length;
    os = request.GetRequestStream();
    os.Write(bytes, 0, bytes.Length);


    GoogleToken token = new GoogleToken();

    HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
    Stream responseStream = webResponse.GetResponseStream();
    StreamReader responseStreamReader = new StreamReader(responseStream);
    string result = responseStreamReader.ReadToEnd();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    token = serializer.Deserialize<GoogleToken>(result);

然后使用toke和refresh令牌创建凭据。

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = yourclientid,
                    ClientSecret = yourclientsecret
                },
                Scopes = new[] { CalendarService.Scope.Calendar }
            });



            var credential = new UserCredential(flow, Environment.UserName, new TokenResponse
            {
                AccessToken = token.access_token,
                RefreshToken = userrefreshtoke
            });


            CalendarService service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "application name",
            });
            var list = service.CalendarList.List().Execute().Items;
            foreach (var c in list)
            {
                var events = service.Events.List(c.Id).Execute().Items.Where(i => i.Start.DateTime >= DateTime.Now).ToList();
                foreach (var e in events)
                {
                }
}

GoogleToken课程:

 public class GoogleToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }       
    }

答案 1 :(得分:0)

根据Google提供的.NET Quickstart sample,您需要下载 client_secret.json ,这是身份验证过程的一部分。检查链接中的整个过程。

下面&#39;用于在.NET中进行事件的片段:

// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
Console.Read();

您还可以在.NET here中阅读更多与oAuth相关的指南。

有关检索日历列表和事件的详细信息,请read this guide