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

问题描述 投票:0回答:1

我正在使用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;
}
c# google-api google-drive-api google-oauth2 google-api-dotnet-client
1个回答
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")
                });
© www.soinside.com 2019 - 2024. All rights reserved.