我想在没有用户的情况下从我的服务器上传图像。我做了盒子应用程序和设置。
我尝试创建 JWT 令牌并获得访问令牌。之后,我尝试从我的 Box 文件中获取文件信息。但是这个 api 返回 404 状态。
我不知道我错过了哪里。如果你知道,请帮助我。
我的代码如下。
package main
import (
"fmt"
"io/ioutil"
"time"
"encoding/json"
"github.com/dgrijalva/jwt-go"
"net/http"
"net/url"
"strings"
)
type BoxToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RestrictedTo []string `json:"restricted_to"`
TokenType string `json:"token_type"`
}
func main() {
token := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.MapClaims{
"iss": "application client id",
"sub": "enterprise id",
"box_sub_type": "enterprise",
"aud": "https://api.box.com/oauth2/token",
"jti": "unique id",
"exp": time.Now().Unix() + 60,
})
token.Header["kid"] = "public key id"
privateKeyData, err := ioutil.ReadFile("private.key")
if err != nil {
panic(err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyData)
if err != nil {
panic(err)
}
// Generate encoded token and send it as response.
tokenStr, err := token.SignedString(key)
if err != nil {
panic(err)
}
//fmt.Println(tokenStr)
values := url.Values{}
values.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
values.Add("client_id", "application client id")
values.Add("client_secret", "application client secret")
values.Add("assertion", tokenStr)
req, err := http.NewRequest(http.MethodPost, "https://api.box.com/oauth2/token", strings.NewReader(values.Encode()))
if err != nil {
panic(err)
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.StatusCode)
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var boxToken BoxToken
if err := json.Unmarshal(responseBody, &boxToken); err != nil {
panic(err)
}
req2, err := http.NewRequest("GET", "https://api.box.com/2.0/files/FILE_ID?fields=id,name", nil)
if err != nil {
panic(err)
}
req2.Header.Add("Authorization", `Bearer `+boxToken.AccessToken)
resp2, err := client.Do(req2)
if err != nil {
panic(err)
}
defer resp2.Body.Close()
fmt.Println(resp2.StatusCode)
responseBody2, err := ioutil.ReadAll(resp2.Body)
if err != nil {
panic(err)
}
fmt.Println(string(responseBody2))
}
标准输出是
404
{"type":"error","status":404,"code":"not_found","context_info":{"errors":[{"reason":"invalid_parameter","name":"item","message":"Invalid value 'f_${FILE_ID}'. 'item' with value 'f_${FILE_ID}' not found"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Not Found","request_id":"3de39rftkndh2qqn"}