Google Calendar V3 hangs when used outside local environment

前端 未结 3 519
失恋的感觉
失恋的感觉 2021-01-26 07:46

I\'m working on a wrapper for the .net version of the Google Calendar API. The authentication is rather simple and working fine locally (localhost:port).

UserCr         


        
3条回答
  •  伪装坚强ぢ
    2021-01-26 08:32

    I am with you. For whatever reason, that also had happen to me. It was a calvary. The code below works for me. It is my own revision of Google API Simple Task ASP.NET sample.

    Add these usings...

    using System.IO;
    using System.Threading;
    
    using Google.Apis.Calendar.v3;
    using Google.Apis.Calendar.v3.Data;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Flows;
    using Google.Apis.Auth.OAuth2.Web;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    

    And these...

    CalendarService service;
    static string gFolder = System.Web.HttpContext.Current.Server.MapPath("/App_Data/MyGoogleStorage");
    
    protected void Page_Load(object sender, EventArgs e)
    {
        IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GetClientConfiguration().Secrets,
                DataStore = new FileDataStore(gFolder),
                Scopes = new[] { CalendarService.Scope.Calendar }
            });
    
        var uri = Request.Url.ToString();
        var code = Request["code"];
        if (code != null)
        {
            var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
    
            // Extract the right state.
            var oauthState = AuthWebUtility.ExtracRedirectFromState(
                flow.DataStore, UserId, Request["state"]).Result;
            Response.Redirect(oauthState);
        }
        else
        {
            var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
                CancellationToken.None).Result;
            if (result.RedirectUri != null)
            {
                // Redirect the user to the authorization server.
                Response.Redirect(result.RedirectUri);
            }
            else
            {
                // The data store contains the user credential, so the user has been already authenticated.
                service = new CalendarService(new BaseClientService.Initializer
                {
                    ApplicationName = "Calendar API Sample",
                    HttpClientInitializer = result.Credential
                });
            }
        }
    
    }
    
    public static GoogleClientSecrets GetClientConfiguration()
    {
        using (var stream = new FileStream(gFolder + @"\client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            return GoogleClientSecrets.Load(stream);
        }
    }
    

    Hope that helps.

提交回复
热议问题