如何获取用于Google存储URL的访问令牌

时间:2020-04-14 02:34:18

标签: google-api google-cloud-storage google-oauth

我正在尝试从此Google存储桶中读取

https://storage.googleapis.com/images.eng.channelmeter.com/avatars/d2d48e49-82be-4cf6-be6e-11ada43c7339

但是我收到此错误:

nice colorful error image

错误如下:

<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
<Details>
Anonymous caller does not have storage.objects.get access to images.eng.channelmeter.com/avatars/d2d48e49-82be-4cf6-be6e-11ada43c7339.
</Details>
</Error>

如何获取可以附加到url的访问令牌?像这样:

https://storage.googleapis.com/images.eng.channelmeter.com/avatars/d2d48e49-82be-4cf6-be6e-11ada43c7339?access_token=“ XXX”

我想我可以使用OAuth库进行一些调用来获取临时/一次性访问令牌,有人知道吗?

更新: 我可以使用以下技术获取AccessToken:https://tanaikech.github.io/2018/12/11/retrieving-access-token-using-service-account-by-googles-oauth2-package-for-golang/

但是当我将?access_token=xxx添加到URL时,我现在得到:

<Error>
<Code>AccessDenied</Code>
<Message>Access denied.</Message>
</Error>

该死。

1 个答案:

答案 0 :(得分:0)

我转载了您的用例。假设您有一个服务帐户的key.json文件,并且在存储桶上具有wright权限。

要授权来自命令行的请求或进行测试,您可以 使用带有以下语法的curl命令:

curl -H“授权:承载ACCESS_TOKEN” “ https://storage.googleapis.com/storage/v1/b/example-bucket/o

对于本地测试,您可以使用gcloud auth application-default print-access-token命令来生成令牌。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    "net/http"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "golang.org/x/oauth2/jwt"
    "log"
)


func serviceAccount(credentialFile string) (*oauth2.Token, error) {
    b, err := ioutil.ReadFile(credentialFile)
    if err != nil {
        return nil, err
    }
    var c = struct {
        Email      string `json:"client_email"`
        PrivateKey string `json:"private_key"`
    }{}
    json.Unmarshal(b, &c)
    config := &jwt.Config{
        Email:      c.Email,
        PrivateKey: []byte(c.PrivateKey),
        Scopes: []string{
            "https://www.googleapis.com/auth/cloud-platform",
        },
        TokenURL: google.JWTTokenURL,
    }
    token, err := config.TokenSource(oauth2.NoContext).Token()
    if err != nil {
        return nil, err
    }
    return token, nil
}

func main() {
    token, err := serviceAccount("key.json") // Please set here
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }


    url := "https://storage.googleapis.com/storage/v1/b/your-bucket/o/your-file?alt=media"

    // Create a Bearer string by appending string access token
    var bearer = "Bearer " + token.AccessToken

    // Create a new request using http
    req, err := http.NewRequest("GET", url, nil)

    // add authorization header to the req

    req.Header.Add("Authorization", bearer)

    // Send req using http Client
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Println("Error on response.\n[ERRO] -", err)
    }

    body, _ := ioutil.ReadAll(resp.Body)
    log.Println(string([]byte(body)))

}