Google Drive API身份验证-在客户端上进行身份验证?

时间:2020-02-27 20:28:56

标签: javascript asp.net authentication google-drive-api

当用户想要通过我的服务访问其Google驱动器时,我在后端调用以下代码。

  public static DriveService GetService(string app_userID)
    {

        //get Credentials from client_secret.json file 
        UserCredential credential;
        var path = HttpContext.Current.Server.MapPath(@"~/client_secret.json");
        using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.
            string credPath = HttpContext.Current.Server.MapPath(@"~/token.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                app_userID,
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }

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

不过,问题是我认为此代码是为在前端应用程序上运行而开发的。我收到以下错误,我认为该程序尝试在后端服务器上打开用于身份验证的网页。

{
"Message": "An error has occurred.",
"ExceptionMessage": "One or more errors occurred.",
"ExceptionType": "System.AggregateException",
"StackTrace": "   at System.Threading.Tasks.Task`1.GetResultCore(Boolean .......GoogleDrive.GoogleDriveFilesRepository.GetService(String tt_userID) in ,,,
"InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Failed to launch browser with \"...(google url)..." for authorization. See inner exception for details.",
    "ExceptionType": "System.NotSupportedException",
    "StackTrace": "   ...
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Access is denied",
        "ExceptionType": "System.ComponentModel.Win32Exception",
        "StackTrace": "   at ...

如何更改,以便最终用户在客户端进行身份验证?请参阅下面的设置。

enter image description here

请注意,如果可能的话,我仍然希望能够从后端调用API。

1 个答案:

答案 0 :(得分:0)

好吧,这就是我最终解决它的方式。

认证必须在客户端完成,因此也必须在Java脚本代码中实现。身份验证将产生一个身份验证代码。

自从我在vue中执行实现以来,我使用了以下库:vue-google-oauth2

如果您想直接用JavaScript实现this tutorial可能会有所帮助(第一部分直到获得“代码”为止)。

验证码只能用于请求访问令牌。在这种情况下,需要使用ASP.NET中实现的API,将身份验证代码传递到后端服务器。

在后端,我将this librarythis implementation一起使用。唯一的例外是我将redirect_uri设置为“ postmessage”。通过这种方法,无需使用redirect_uri就可以获取访问令牌。不知道redirect_uri的目的。但是,使用“ postmessage”时,无需在Google控制台中设置redirect_uri。

我在服务器和Web客户端上使用了相同的clientID。效果很好,但是我不确定那是否应该是这样。

最后,您需要一定程度地了解oauth2才能实现oauth2。 this page底部的图表提供了很好的概述。但是,如果您打算在实际的生产环境中实现此目的,则应确保您掌握了该主题或得到了相关人员的帮助。