代码之家  ›  专栏  ›  技术社区  ›  Sahand

如何通过谷歌云打印认证

  •  1
  • Sahand  · 技术社区  · 8 年前

    我正在制作一个应用程序,需要通过谷歌云打印将打印作业发送给我拥有的两台打印机(即,打印机总是同一台,不属于用户)。我已经用谷歌云打印设置了打印机,现在可以从我的谷歌账户访问。 enter image description here

    现在,我如何通过API访问该帐户的打印机?我找到了一些文件 here 也就是说,我需要在提出请求时对自己进行身份验证。 在我看来 身份验证应该用 OAuth2 .但对于初学者来说,缺乏如何做到这一点的指导。我已经获得了OAuth客户端ID和机密(OAuth链接中的第一步)。但是对于第二步,我不知道该怎么做。

    上面写着:

    在你的应用程序可以使用谷歌浏览器访问私人数据之前 API,它必须获得一个访问令牌,该令牌授予对该API的访问权限。A. 单个访问令牌可以向多个用户授予不同程度的访问权限 API。

    但没有解释如何获得这个访问令牌。我看着 this 所以我想问OP是从哪里得到这个访问令牌的,但我不明白他是怎么做到的。

    PS.打印功能由firebase功能触发。考虑到firebase也是由谷歌制造的,这能帮助我们获得访问令牌吗?

    2 回复  |  直到 8 年前
        1
  •  1
  •   user10595796 Miguel Mota    7 年前

    我遇到了同样的问题,并提出了以下两步解决方案:

    1. 在应用程序中创建OAuth2客户端 Google Cloud Console 如上所述 here 并从控制台下载其客户端凭据,然后复制&将其json内容转换为 credJSON 在下面的代码片段中。
    2. 运行下面的代码。
      • 遵循auth链接,授权您的OAuth2客户端使用您的谷歌帐户访问谷歌云打印机。
      • 复印及;将身份验证代码粘贴到脚本中
      • 获得刷新令牌后,确保将其存储在变量中 refreshToken
      • 别忘了更新代理名称。
    package main
    
    import (
        "context"
        "fmt"
        "log"
    
        "github.com/google/cloud-print-connector/gcp"
        "github.com/google/cloud-print-connector/lib"
        "github.com/google/uuid"
        "golang.org/x/oauth2"
        "golang.org/x/oauth2/google"
    )
    
    var (
        credJSON     = ``
        refreshToken = ""
    
        // Find the proxy in the Advanced Details of your printer at https://www.google.com/cloudprint#printers
        proxy = "HP"
    )
    
    func main() {
        // Obtain the OAuth config
        config, err := google.ConfigFromJSON([]byte(credJSON), gcp.ScopeCloudPrint)
        if err != nil {
            log.Fatalf("Failed to obtain OAuth config: %v", err)
        }
    
        // If no request token is present, obtain a new one
        if refreshToken == "" {
            // Get the auth link
            authLink := config.AuthCodeURL(uuid.New().String(), oauth2.AccessTypeOffline)
            log.Printf("Follow the link to obtain an auth code: %s", authLink)
    
            fmt.Printf("Paste your auth code here: ")
            var code string
            fmt.Scanln(&code)
    
            // Get a token form the auth code
            token, err := config.Exchange(context.Background(), code, oauth2.AccessTypeOffline)
            if err != nil {
                log.Fatalf("Failed to obtain OAuth token: %v", err)
            }
            if token.RefreshToken != "" {
                refreshToken = token.RefreshToken
            } else {
                refreshToken = token.AccessToken
            }
            log.Printf("Refresh token: %s", refreshToken)
        }
    
        // Connect to Google Cloud Print
        jobCh := make(chan *lib.Job)
        client, err := gcp.NewGoogleCloudPrint(lib.DefaultConfig.GCPBaseURL, refreshToken, refreshToken, proxy, config.ClientID, config.ClientSecret, config.Endpoint.AuthURL, config.Endpoint.TokenURL, lib.DefaultConfig.NativeJobQueueSize, jobCh, true)
        if err != nil {
            log.Fatalf("Failed to connect to GCP: %v", err)
        }
    
        // List all printers
        printers, _, err := client.ListPrinters()
        if err != nil {
            log.Fatalf("Failed to list printers: %v", err)
        }
        for _, p := range printers {
            log.Printf("Name: %s UUID: %s", p.Name, p.UUID)
        }
    }
    
        2
  •  0
  •   Anirudh Saria    7 年前

    请参阅以下文件:

    https://developers.google.com/identity/protocols/OAuth2ServiceAccount?authuser=1
    

    我遵循了文档中指定的相同步骤,并且能够获得访问令牌。首先创建谷歌服务账户,选择提供新私钥。您将拥有服务帐户电子邮件地址和私钥。使用这些凭据,您可以获得访问令牌。下面是Golang的源代码,这肯定会对你有所帮助。

    package main
    
    import (
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "net/http"
    "encoding/json"
    "bytes"
    )
    
    type MyCustomClaims struct {
        Scope string `json:"scope,omitempty"`
        jwt.StandardClaims
    }
    
    type Toke struct {
        Access string `json:"access_token,omitempty"`
        Type string `json:"token_type,omitempty"`
        Expire string `json:"expires_in,omitempty"`
    }
    
    func main() {
    
        key := []byte("<your private key>")
    
        key1, _ := jwt.ParseRSAPrivateKeyFromPEM(key)
    
        claims := MyCustomClaims{
            "https://www.googleapis.com/auth/cloudprint",
            jwt.StandardClaims{
                IssuedAt: <currrent-epoch-time>,         // eg 1234566000
                ExpiresAt: <currrent-epoch-time + 3600>, // 3600 secs = 1hour, so expires in 1 hour, eg 1234569600
                Issuer:    "<your service account email>",
                Audience: "https://www.googleapis.com/oauth2/v4/token",
            },
        }
        token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
        ss, err := token.SignedString(key1)
        if err != nil {
            fmt.Println(err)
        }
    
        fmt.Println(ss)
        url := "https://www.googleapis.com/oauth2/v4/token"
        any := "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" + ss
        a := []byte(any)
        b := bytes.NewBuffer(a)
        var tok Toke
    
        req, err := http.NewRequest("POST", url, b)
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    
        client := &http.Client{}
    
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        } else {
            json.NewDecoder(resp.Body).Decode(&tok)
        }
        fmt.Println("----------- Access Token -----------------")
        fmt.Println("Access: ", tok.Access)
    }