如何使用不同的用户帐户访问Google API? (ASP.NET MVC)

时间:2020-05-27 09:00:20

标签: c# google-api google-drive-api google-oauth google-api-dotnet-client

我正在用ASP.NET MVC(C#)开发一个Web应用程序,该应用程序可与Google Drive API一起使用。我已经使用OAuth 2.0进行了整个身份验证,并且与API的配合非常完美。问题在于,登录并授予我的应用程序工作权限后,如果我从另一台计算机访问我的网站的URL,它不会要求授权,而是可以使用最初已经通过身份验证的帐户。

换句话说,我需要能够访问我的网站并以不同的用户帐户使用Google云端硬盘。每个人都可以在此进行身份验证并使用他们的Google云端硬盘。

代码如下:

public static Google.Apis.Drive.v3.DriveService GetService_v3()
{
    UserCredential credential;
    using (var stream = new FileStream(HostingEnvironment.MapPath("~/client_secret.json"), FileMode.Open, FileAccess.Read))
    {
        String FolderPath = HostingEnvironment.MapPath("~");
        String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(FilePath, true)).Result;
    }

    //Create Drive API service.
    Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "GoogleDriveRestAPI-v3",
    });

    return service;
}

1 个答案:

答案 0 :(得分:0)

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(FilePath, true)).Result;
    }

文件数据存储区将当前登录用户的凭据存储到由“用户”表示的计算机上的%appdata%中。因此,如果您想要一个以上的用户,则需要将“用户”更改为其他用户。

请注意,GoogleWebAuthorizationBroker.AuthorizeAsync用于已安装的应用程序,它将在用户计算机上打开授权浏览器,不能用于托管网站,它将尝试打开网络浏览器供用户在服务器上进行身份验证将不起作用。

使用

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")
                });

web-applications-asp.net-mvc

相关问题