谷歌日历API认证.NET浏览器窗口 [英] Google Calendar API Authentication .NET browser window

查看:316
本文介绍了谷歌日历API认证.NET浏览器窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是最新版本的谷歌.NET客户端API(V1.81)的。我尝试使用下面的代码连接到日历服务

I am using the latest version of the Google .NET Client API (v1.81). I am trying to connect to the Calendar Service using the following code

    var calendarService = new CalendarService(new BaseClientService.Initializer
    {
        HttpClientInitializer = GetCredential(),
        ApplicationName = "MyApp"
    });

    public UserCredential GetCredential()
    {
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets { ClientId = _clientId, ClientSecret = _clientSecret },
            new[] { CalendarService.Scope.Calendar }.ToList(), "user", CancellationToken.None,
            new FileDataStore("Drive.Auth.Store")).Result;

        return credential;
    }

当我这样做,它会打开一个新的浏览器窗口,并要求我进行身份验证。我以前验证,关键是通过FileDataStore存储和检索。

When I do this it opens a new Browser Window and asks for me to authenticate. I have previously authenticated and the key is stored and retrieved via FileDataStore.

为什么它会问我再次进行身份验证?这个问题是因为这个代码需要在后台服务运行,因此它不能打开的浏览器标签。

Why would it be asking me to authenticate again? The problem is because this code needs to run in a background service so it can't open browser tabs.

我现在得到的另外一个问题,当我尝试并授权它开辟了一个新的浏览器窗口,我选择我的凭据,但随后在登录页告诉我

Another issue I now am getting, when I try and authorise it opens up a new browser window, I select my credentials but the login page then tells me

在请求重定向URI:的http://本地主机:51773 /授权/ 没有匹配的注册重定向URI

"The redirect URI in the request: http://localhost:51773/authorize/ did not match a registered redirect URI"

为什么试图使用授权网址,而不是AuthCallbackController。它似乎也随意改变重定向URI使注册不可能的端口号。

Why is it trying to use the Authorize url and not the AuthCallbackController. It also seems to randomly change the port number of the redirect uri making registering it impossible.

最终的问题可能是,如果我有一个Web应用程序,我希望用户在通过网络页面中使用其凭据登录,然后重复使用在服务器上的后台任务以后这些凭据,我怎么去的?我找不到任何相关的示例应用来展示如何。它出现在FileDataStore不存储的凭证,以便它们可以被重复使用。我也实现我自己的DataStore从而节省了他们在其中似乎并没有任何工作数据库。

The ultimate question probably is, if I have a web app and I want the users to sign in using their credentials via the web page and then reuse those credentials at a later date in a background task on the server, how do I go about that? I couldn't find any relevant sample app to show how. It appears the FileDataStore does not store the credentials so they can be reused. I have also implemented my own DataStore which saves them in the database which doesn't seem to work either.

进一步挖掘到这一点,看来我需要offline_access。我已经实现这个一样谷歌分析的OAuth与接入类型=离线在C#中但它仍然提示。我如何重用offline_access刷新令牌?

Digging further into this it appears I need offline_access. I have implemented this the same as Google Analytics OAuth with AccessType = Offline in C# but it still prompts. How to I reuse the offline_access refresh token?

推荐答案

您是正确的,你需要创建自己的小鬼实现Idatastore的。这将允许您将刷新令牌保存到数据库,并在以后使用它。

You are correct you need to create your own imp implementation of Idatastore. This will allow you to save your refresh token to the database and use it later.

下面是一个非常粗略的例子

Here is a very rough example

/// 
 /// Saved data store that implements . 
 /// This Saved data store stores a StoredResponse object.
 /// 
    class SavedDataStore : IDataStore
    {
        public StoredResponse _storedResponse { get; set; }
        /// 
        /// Constructs Load previously saved StoredResponse.
        /// 
        ///Stored response
        public SavedDataStore(StoredResponse pResponse)
        {
            this._storedResponse = pResponse;
        }
        public SavedDataStore()
        {
            this._storedResponse = new StoredResponse();
        }
        /// 
        /// Stores the given value. into storedResponse
        /// .
        /// 
        ///The type to store in the data store
        ///The key
        ///The value to store in the data store
        public Task StoreAsync(string key, T value)
        {
            var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
            JObject jObject = JObject.Parse(serialized);
            // storing access token
            var test = jObject.SelectToken("access_token");
            if (test != null)
            {
                this._storedResponse.access_token = (string)test;
            }
            // storing token type
            test = jObject.SelectToken("token_type");
            if (test != null)
            {
                this._storedResponse.token_type = (string)test;
            }
            test = jObject.SelectToken("expires_in");
            if (test != null)
            {
                this._storedResponse.expires_in = (long?)test;
            }
            test = jObject.SelectToken("refresh_token");
            if (test != null)
            {
                this._storedResponse.refresh_token = (string)test;
            }
            test = jObject.SelectToken("Issued");
            if (test != null)
            {
                this._storedResponse.Issued = (string)test;
            }
            return TaskEx.Delay(0);
        }

        /// 
        /// Deletes StoredResponse.
        /// 
        ///The key to delete from the data store
        public Task DeleteAsync(string key)
        {
            this._storedResponse = new StoredResponse();
            return TaskEx.Delay(0);
        }

        /// 
        /// Returns the stored value for_storedResponse      
        ///The type to retrieve
        ///The key to retrieve from the data store
        /// The stored object
        public Task GetAsync(string key)
        {
            TaskCompletionSource tcs = new TaskCompletionSource();
            try
            {
                string JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(this._storedResponse);
                tcs.SetResult(Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize(JsonData));
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
            return tcs.Task;
        }

        /// 
        /// Clears all values in the data store. 
        /// 
        public Task ClearAsync()
        {
            this._storedResponse = new StoredResponse();
            return TaskEx.Delay(0);
        }

        ///// Creates a unique stored key based on the key and the class type.
        /////The object key
        /////The type to store or retrieve
        //public static string GenerateStoredKey(string key, Type t)
        //{
        //    return string.Format("{0}-{1}", t.FullName, key);
        //}
    }

现在,而不是调用filedatastore你会打电话给savedDataStore

now instead of calling filedatastore you will call savedDataStore

 //Now we load our saved refreshToken. Probably from the DB someplace but this works
  StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
 // Now we pass a SavedDatastore with our StoredResponse.

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
             new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
              new[] { DriveService.Scope.Drive,
                DriveService.Scope.DriveFile },
              "user",
              CancellationToken.None,
               new SavedDataStore(myStoredResponse)).Result; }



我对这个教程和示例项目。目前与谷歌的作用域驱动器可以很容易地改变这些,示例项目是在底部。 谷歌的oauth2 C#

这篇关于谷歌日历API认证.NET浏览器窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆