C#WebApi 2服务器端的Google Drive身份验证

时间:2018-06-19 08:43:00

标签: c# google-api google-drive-api asp.net-web-api2 google-api-dotnet-client

我正在开发一个使用谷歌驱动API的网络API,在我的本地计算机上,首先运行它将我重定向到谷歌页面进行身份验证,然后工作正常。现在我想将我的代码发布到Azure,在我发布它之后,同样的功能失败了,因为我可以进行身份​​验证。如何在服务器上执行此身份验证?

我已经关注了.NET快速入门(https://developers.google.com/drive/api/v3/quickstart/dotnet),这是我的代码:

using (var stream =
            new FileStream($@"{dir}\client_secret.json", FileMode.Open, FileAccess.Read))
        {
            var cred = GoogleClientSecrets.Load(stream).Secrets;
            Credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
                cred,
                Scopes,
                "user",
                CancellationToken.None).Result;
        }
        service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = Credentials,
            ApplicationName = ApplicationName,
        });
}

1 个答案:

答案 0 :(得分:1)

您所遵循的教程适用于.NET控制台应用程序,这是本机应用程序而非Web应用程序。 GoogleWebAuthorizationBroker用于已安装的应用程序。它适用于localhost,因为它能够在您的计算机上生成浏览器窗口。这不适用于托管环境,因为它无法在服务器上生成Web浏览器。

您应该关注此示例Web applications

using System;
using System.Web.Mvc;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;

namespace Google.Apis.Sample.MVC4
{
    public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }
}

请注意,您可能需要更改filedatastore存储凭据的位置,该凭据取决于您具有写入权限的位置。这可以通过提供要存储它的文件夹的路径来完成。

new FileDataStore(@"c:\datastore",true)