GoogleWebAuthorizationBroker在MVC对于谷歌驱动器访问 [英] GoogleWebAuthorizationBroker in MVC For Google Drive Access

查看:258
本文介绍了GoogleWebAuthorizationBroker在MVC对于谷歌驱动器访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持试图从MVC应用程序访问特定的谷歌帐户的驱动器。所有我需要的是MVC的Web应用程序来访问我的谷歌驱动器扫描了一些文件和修改基于谷歌的驱动器的内容数据库。问题是在IIS作为GoogleWebAuthorizationBroker试图如果一个Windows应用程序,打开浏览器,但似乎并没有能够做到这一点通过IIS即使它没有这将是服务器端驱动器无法进行验证运行时。

在理想情况下我也不会在所有验证这个程序,但是如果它有干什么去通过那我怎么让它在IIS工作?

UserCredential凭证= GoogleWebAuthorizationBroker.AuthorizeAsync(
    新ClientSecrets
            {
                客户端Id =添加my_id
                ClientSecret =My_Secret
            },
            新的[] {} DriveService.Scope.Drive,
            用户,
            CancellationToken.None,数据存储:新FileDataStore(使用Server.Mappath(〜/ App_Data文件/ Google资料)))结果。


解决方案

我得到这个工作,能够使网站使用我的帐户来访问谷歌驱动器,而不要求用户登录或授权。

首先,请点击此链接来获得与谷歌MVC API工作:

<一个href=\"https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web_applications\">https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web_applications

有在示例code的一个问题,在HomeController的

 公共异步任务IndexAsync(的CancellationToken的CancellationToken)

应该是:

 公共异步任务&LT;&的ActionResult GT; IndexAsync(的CancellationToken的CancellationToken)

在这之后,我创建了一个MemoryDataStore(见末code)这是一个稍微修饰从MemoryDataStore张贴在这里:

<一个href=\"http://conficient.word$p$pss.com/2014/06/18/using-google-drive-api-with-c-part-2/\">http://conficient.word$p$pss.com/2014/06/18/using-google-drive-api-with-c-part-2/

一旦你这样做,你捕捉正在使用的帐户的刷新令牌,以及与此店更换存储时进行身份验证:

 私有静态只读IAuthorization codeFLOW流量=
        新GoogleAuthorization codeFLOW(新GoogleAuthorization codeFlow.Initializer
            {
                ClientSecrets =新ClientSecrets
                {
                    客户端Id =客户端ID,
                    ClientSecret = clientSecret
                },
                范围=新[] {} DriveService.Scope.Drive,
                //数据存储=新FileDataStore(Drive.Api.Auth.Store)
                数据存储=新GDriveMemoryDataStore(commonUser,refreshToken)
            });

下面commonUser是您选择的predefined用户ID。请务必修改GetUserID()方法返回相同commonUser:

 公众覆盖字符串GetUserId(控制器控制器)
    {
        返回commonUser;
    }

一旦做到这一点,谷歌驱动器将停止要求用户登录和授权应用程序。

下面是我的MemoryDataStore code:

  ///&LT;总结&gt;
 ///处理内部令牌存储,文件系统旁路
 ///&LT; /总结&gt;
内部类GDriveMemoryDataStore:IDataStore
 {
     私人字典&LT;字符串,TokenResponse&GT; _商店;
     私人字典&LT;字符串,字符串&GT; _stringStore;     //私钥密码:notasecret     公共GDriveMemoryDataStore()
     {
         _Store =新词典&LT;字符串,TokenResponse&GT;();
         _stringStore =新词典&LT;字符串,字符串&GT;();
     }     公共GDriveMemoryDataStore(字符串键,字符串refreshToken)
     {
         如果(string.IsNullOrEmpty(键))
             抛出新的ArgumentNullException(钥匙);
         如果(string.IsNullOrEmpty(refreshToken))
             抛出新的ArgumentNullException(refreshToken);         _Store =新词典&LT;字符串,TokenResponse&GT;();         //添加新条目
         StoreAsync&LT; TokenResponse&GT;(键,
             新TokenResponse(){RefreshToken = refreshToken,TokenType =旗手})等待();
     }     ///&LT;总结&gt;
     ///移除所有项目
     ///&LT; /总结&gt;
     ///&LT;&回报GT;&LT; /回报&GT;
     公共异步任务ClearAsync()
     {
         等待Task.Run(()=&GT;
         {
             _store.Clear();
             _stringStore.Clear();
         });
     }     ///&LT;总结&gt;
     ///删除单个条目
     ///&LT; /总结&gt;
     ///&LT; typeparam NAME =T&GT;&LT; / typeparam&GT;
     ///&LT; PARAM NAME =键&GT;&LT; /参数&GT;
     ///&LT;&回报GT;&LT; /回报&GT;
     公共异步任务DeleteAsync&LT; T&GT;(字符串键)
     {
         等待Task.Run(()=&GT;
         {
            //检查类型
             AssertCorrectType&LT; T&GT;();             如果(typeof运算(T)== typeof运算(字符串))
             {
                 如果(_stringStore.ContainsKey(键))
                     _stringStore.Remove(键);
             }
             否则,如果(_store.ContainsKey(键))
             {
                 _store.Remove(键);
             }
         });
     }     ///&LT;总结&gt;
     ///获取对象
     ///&LT; /总结&gt;
     ///&LT; typeparam NAME =T&GT;&LT; / typeparam&GT;
     ///&LT; PARAM NAME =键&GT;&LT; /参数&GT;
     ///&LT;&回报GT;&LT; /回报&GT;
     公共异步任务&LT; T&GT; GetAsync&LT; T&GT;(字符串键)
     {
         //检查类型
         AssertCorrectType&LT; T&GT;();         如果(typeof运算(T)== typeof运算(字符串))
         {
             如果(_stringStore.ContainsKey(键))
                 返回等待Task.Run(()=&GT; {回报(T)(对象)_stringStore [关键];});
         }
         否则,如果(_store.ContainsKey(键))
         {
             返回等待Task.Run(()=&GT; {回报(T)(对象)_Store [关键];});
         }
         //键未找到
         返回默认(T);
     }     ///&LT;总结&gt;
     ///添加键/值/更新值
     ///&LT; /总结&gt;
     ///&LT; typeparam NAME =T&GT;&LT; / typeparam&GT;
     ///&LT; PARAM NAME =键&GT;&LT; /参数&GT;
     ///&LT; PARAM NAME =值&GT;&LT; /参数&GT;
     ///&LT;&回报GT;&LT; /回报&GT;
     公共任务StoreAsync&LT; T&GT;(字符串键,T值)
     {
         返回Task.Run(()=&GT;
         {
             如果(typeof运算(T)== typeof运算(字符串))
             {
                 如果(_stringStore.ContainsKey(键))
                     _stringStore [关键] =(字符串)(对象)的价值;
                 其他
                     _stringStore.Add(键,(串)(对象)值);
             }其他
             {
                 如果(_store.ContainsKey(键))
                     _Store [关键] =(TokenResponse)(对象)的价值;
                 其他
                     _store.Add(键,(TokenResponse)(对象)值);
             }
         });
     }     ///&LT;总结&gt;
     ///验证我们可以存储这种类型
     ///&LT; /总结&gt;
     ///&LT; typeparam NAME =T&GT;&LT; / typeparam&GT;
     私人无效AssertCorrectType&LT; T&GT;()
     {
         如果(typeof运算(T)= typeof运算(TokenResponse)及!&安培; typeof运算(T)= typeof运算(字符串)!)
             抛出新NotImplementedException(typeof运算(T)的ToString());
     }
 }

I'm stuck trying to access a specific Google drive account from a MVC app. All I need is for the MVC web app to access my google drive scan for a few files and alter the database based on the contents of the google drive. The problem is when running in IIS the drive cannot be authenticated as GoogleWebAuthorizationBroker tries to open browser if its a windows app but doesn't seem to be able to do that through IIS and even if it did it would be server side.

Ideally I would not have to authenticate this app at all, but if it has do go through that then how do I make it work in IIS?

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets
            {
                ClientId = "MY_ID",
                ClientSecret = "My_Secret"
            },
            new[] { DriveService.Scope.Drive },
            "user",
            CancellationToken.None, dataStore: new FileDataStore(Server.MapPath("~/app_data/googledata"))).Result;

解决方案

I got this to work, was able to enable the web site to access Google drive using my account without asking users to login or authorize.

First of all, follow this link to get Google API work with MVC:

https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web_applications

There is a problem in the Sample code, in HomeController

 public async Task IndexAsync(CancellationToken cancellationToken)

Should be:

 public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)

After that, I created a MemoryDataStore (see code at the end) that is a slightly modification from the MemoryDataStore posted here:

http://conficient.wordpress.com/2014/06/18/using-google-drive-api-with-c-part-2/

Once you do that, capture the refresh token of the account you are using, and replace the store with this store when authenticate:

    private static readonly IAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = clientID,
                    ClientSecret = clientSecret
                },
                Scopes = new[] { DriveService.Scope.Drive },
                //DataStore = new FileDataStore("Drive.Api.Auth.Store")
                DataStore = new GDriveMemoryDataStore(commonUser, refreshToken)
            });

Here commonUser is a predefined user id of your chosen. Please make sure to modify the GetUserID() method to return the same commonUser:

 public override string GetUserId(Controller controller)
    {
        return commonUser;
    }

Once this is done, Google drive will stop asking user to login and authorize the app.

Here is my MemoryDataStore code:

 /// <summary>
 /// Handles internal token storage, bypassing filesystem
 /// </summary>
internal class GDriveMemoryDataStore : IDataStore
 {
     private Dictionary<string, TokenResponse> _store;
     private Dictionary<string, string> _stringStore;

     //private key password: notasecret

     public GDriveMemoryDataStore()
     {
         _store = new Dictionary<string, TokenResponse>();
         _stringStore = new Dictionary<string, string>();
     }

     public GDriveMemoryDataStore(string key, string refreshToken)
     {
         if (string.IsNullOrEmpty(key))
             throw new ArgumentNullException("key");
         if (string.IsNullOrEmpty(refreshToken))
             throw new ArgumentNullException("refreshToken");

         _store = new Dictionary<string, TokenResponse>();

         // add new entry
         StoreAsync<TokenResponse>(key,
             new TokenResponse() { RefreshToken = refreshToken, TokenType = "Bearer" }).Wait();
     }

     /// <summary>
     /// Remove all items
     /// </summary>
     /// <returns></returns>
     public async Task ClearAsync()
     {
         await Task.Run(() =>
         {
             _store.Clear();
             _stringStore.Clear();
         });
     }

     /// <summary>
     /// Remove single entry
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="key"></param>
     /// <returns></returns>
     public async Task DeleteAsync<T>(string key)
     {
         await Task.Run(() =>
         {
            // check type
             AssertCorrectType<T>();

             if (typeof(T) == typeof(string))
             {
                 if (_stringStore.ContainsKey(key))
                     _stringStore.Remove(key);                 
             }
             else if (_store.ContainsKey(key))
             {
                 _store.Remove(key);
             }
         });
     }

     /// <summary>
     /// Obtain object
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="key"></param>
     /// <returns></returns>
     public async Task<T> GetAsync<T>(string key)
     {
         // check type
         AssertCorrectType<T>();

         if (typeof(T) == typeof(string))
         {
             if (_stringStore.ContainsKey(key))
                 return await Task.Run(() => { return (T)(object)_stringStore[key]; });
         }
         else if (_store.ContainsKey(key))
         {
             return await Task.Run(() => { return (T)(object)_store[key]; });
         }
         // key not found
         return default(T);
     }

     /// <summary>
     /// Add/update value for key/value
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="key"></param>
     /// <param name="value"></param>
     /// <returns></returns>
     public Task StoreAsync<T>(string key, T value)
     {
         return Task.Run(() =>
         {
             if (typeof(T) == typeof(string))
             {
                 if (_stringStore.ContainsKey(key))
                     _stringStore[key] = (string)(object)value;
                 else
                     _stringStore.Add(key, (string)(object)value);
             } else
             {
                 if (_store.ContainsKey(key))
                     _store[key] = (TokenResponse)(object)value;
                 else
                     _store.Add(key, (TokenResponse)(object)value);
             }
         });
     }

     /// <summary>
     /// Validate we can store this type
     /// </summary>
     /// <typeparam name="T"></typeparam>
     private void AssertCorrectType<T>()
     {
         if (typeof(T) != typeof(TokenResponse) && typeof(T) != typeof(string)) 
             throw new NotImplementedException(typeof(T).ToString());
     }
 }

这篇关于GoogleWebAuthorizationBroker在MVC对于谷歌驱动器访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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