当前位置: 首页 > 知识库问答 >
问题:

401未经授权-谷歌驱动器API

姬歌者
2023-03-14

我是第一次使用谷歌API,我在尝试下载文件对象“下载Url”属性的文件时遇到问题。我当前正在使用“服务帐户”选项以及关联的服务帐户电子邮件和 P12 证书。

但是,URL返回“https://doc-08-68-docs.googleusercontent.com/docs/securesc/bteg36c1tifegg79l2ov17og25612tet/gk7kn52ahe4d0to7d6hte9f0f2hv47e4/1434132000000/11750183130219432819/11750183130219432819/0BziIKv2_NWCxc3RhcnRlcl9maWxl?e=download

Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2

Namespace Videos

    Partial Class List
        Inherits System.Web.UI.UserControl

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Const serviceAccountEmail As String = "@developer.gserviceaccount.com"

            Dim certificate = New X509Certificate2(
                Server.MapPath("~/bin/key.p12"),
                "notasecret",
                X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
            )

            Dim credential = New ServiceAccountCredential(
               New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
                   .Scopes = New String() {DriveService.Scope.Drive}
               }.FromCertificate(certificate)
            )

            Dim service = New DriveService(
                New BaseClientService.Initializer() With {
                    .HttpClientInitializer = credential,
                    .ApplicationName = "LexVid-VideoEncode/1.0"
                }
            )

            UxFiles.DataSource = RetrieveAllFiles(service)
            UxFiles.DataBind()

        End Sub

        Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)

            Dim result = New List(Of Data.File)()
            Dim request As FilesResource.ListRequest = service.Files.List()

            Do

                Try

                    Dim files As FileList = request.Execute()

                    result.AddRange(files.Items)
                    request.PageToken = files.NextPageToken

                Catch e As Exception
                    request.PageToken = Nothing
                End Try

            Loop While (Not String.IsNullOrEmpty(request.PageToken))

            Return result

        End Function


        Public Shared Function DownloadFile(ByVal service As DriveService, ByVal file As Data.File) As System.IO.Stream

            If (Not String.IsNullOrEmpty(file.DownloadUrl)) Then

                Try

                    Dim x = service.HttpClient.GetByteArrayAsync(file.DownloadUrl)
                    Dim result As [Byte]() = x.Result

                    Return New MemoryStream(result)

                Catch e As Exception
                    Return Nothing
                End Try

            Else
                Return Nothing
            End If

        End Function

        Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound

            Dim dataItem = CType(e.Item.DataItem, Data.File)

            Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
            file.NavigateUrl = dataItem.DownloadUrl
            file.Text = dataItem.Title

        End Sub

    End Class

End Namespace

共有1个答案

阎扬
2023-03-14

我通过一些尝试和错误解决了这个问题。虽然我现在正在手动构建链接,但请求令牌甚至不再需要。但是,我在这里发布,以防其他人希望解决类似的问题。

Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Threading

Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2

Namespace Videos

    Partial Class List
        Inherits System.Web.UI.UserControl

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Const serviceAccountEmail As String = "@developer.gserviceaccount.com"

            Dim certificate = New X509Certificate2(
                Server.MapPath("~/bin/key.p12"),
                "notasecret",
                X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
            )

            Dim credential As ServiceAccountCredential = New ServiceAccountCredential(
            New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
                .Scopes = New String() {DriveService.Scope.Drive}
            }.FromCertificate(certificate)
            )

            If (credential.RequestAccessTokenAsync(CancellationToken.None).Result) Then

                Dim service = New DriveService(
                    New BaseClientService.Initializer() With {
                        .HttpClientInitializer = credential,
                        .ApplicationName = "LexVid-VideoEncode/1.0"
                    }
                )

                UxFiles.DataSource = RetrieveAllFiles(service)
                UxFiles.DataBind()

            End If

        End Sub

        Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)

            Dim result = New List(Of Data.File)()
            Dim request As FilesResource.ListRequest = service.Files.List()

            Do

                Try

                    Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
                    request.Q = String.Format("'{0}' in parents and trashed=false", folderID)
                    Dim files As FileList = request.Execute()

                    result.AddRange(files.Items)
                    request.PageToken = files.NextPageToken

                Catch e As Exception
                    request.PageToken = Nothing
                End Try

            Loop While (Not String.IsNullOrEmpty(request.PageToken))

            Return result

        End Function

        Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound

            Dim dataItem = CType(e.Item.DataItem, Data.File)

            Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"

            Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
            file.NavigateUrl = String.Format("http://googledrive.com/host/{0}/{1}", folderID, dataItem.Title)
            ' Large files prompt for virus scan; no bypass available.
            ' file.NavigateUrl = String.Format("https://drive.google.com/uc?export=download&id={0}", dataItem.Id)
            file.Text = dataItem.Title

        End Sub

    End Class

End Namespace
 类似资料:
  • 我用这个代码通过OAuth 2.0授权谷歌 oauthswift=OAuth2Swift(consumerKey:“984813079630-f828a92sqtl5lgumd4kgp9i30bs9og09.apps.googleusercontent.com”,ConsumerCret:“AIzaSyD13MBv78yWIjl4TX9jOOT9AWuEkYdVSPQ”,授权URL:https:/

  • 我正在尝试在Android设备上使用一个简单的电话差距应用程序。因此,我遵循了所有步骤,创建了一个项目,该应用程序成功地与GCM服务器通信,并使用我的项目编号获取注册ID。 问题是我不能从服务器端与GCM通信。我最初是在Perl中这样做的,但是即使是GCM文档中的curl example也返回“401”。 他们的API访问密钥被列入了白名单,我试着删除它并创建新的几次。甚至尝试使用浏览器密钥而不是

  • 我的代码:GoogleCredential凭据 credential.refreshToken() 错误日志: 创建服务号的步骤: 我在凭据中的oauth 2.0中创建了一个Web应用程序 然后我用客户端ID创建了一个服务号 现在我正在使用这个服务号和从它生成的p12证书来验证和创建Google凭据的对象 一旦刷新令牌,我就给了我401例外。 在这种情况下,任何帮助都会受到感激

  • 在我的Java/Ionic2应用程序中,我通过REST服务请求使用刷新令牌对Google Drive进行身份验证,然后使用access_type=offline,如下所述:https://developers.Google.com/identity/protocols/oauth2webserver#refresh。 服务器响应200 OK,所以它给我一个刷新和一个访问令牌,只是在我第一次请求访问

  • 我想使用爪哇谷歌驱动器API。我尝试了这段代码: 但是我得到了这个错误: 我使用以下配置: 你能告诉我怎么解决这个问题吗?

  • null null 使用NodePort服务公开Keycloak。 应用程序使用istio入口网关公开。 Keycloak服务器版本:9.0.0。