1

我正在尝试使用 App Store Connect API。根据文档,首先我尝试生成 JWT 令牌。这是golang中的代码:

    package main

    import (
        "fmt"
        "io/ioutil"
        "log"
        "time"
        "github.com/dgrijalva/jwt-go"
    )
var iss = "xxxxxxxxxxxxxxxxxxxxx"
var kid = "xxxxx"

func main() {

        bytes, err := ioutil.ReadFile("AuthKey.p8")
        if err!=nil {
            fmt.Println(err)
        }

        token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
            "iss": iss,
            "exp": time.Now().Unix()+6000,
            "aud": "appstoreconnect-v1",
        })

        token.Header["kid"] = kid

        tokenString, err := token.SignedString(bytes)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(tokenString)

    }

AuthKey.p8 - 来自https://appstoreconnect.apple.com/access/api的 p8 私钥

似乎 jwt lib 不能在签名键上使用这个 p8,所以我收到错误: key is of invalid type

也许有人已经有同样的问题?或者有其他语言的例子?

UPD: 在此建议之后,我已将代码更新为:

func main() {

    bytes, err := ioutil.ReadFile("AuthKey.p8")
    if err!=nil {
        fmt.Println(err)
    }

    block, _ := pem.Decode(bytes)
    key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    if err != nil {
        log.Fatal(err)
    }

    token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
        "iss": iss,
        "exp": time.Now().Unix()+6000,
        "aud": "appstoreconnect-v1",
    })

    token.Header["kid"] = kid

    tokenString, err := token.SignedString(key)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(tokenString)

}

并获得 JWT 令牌,但是当我尝试使用它时,它从苹果 api 获得了 401。

 {
        "errors": [{
                "status": "401",
                "code": "NOT_AUTHORIZED",
                "title": "Authentication credentials are missing or invalid.",
                "detail": "Provide a properly configured and signed bearer token, and make sure that it has not expired. Learn more about Generating Tokens for API Requests https://developer.apple.com/go/?id=api-generating-tokens"
        }]
}
4

2 回答 2

1

似乎来自 jwt-go 库的问题。

作者说:

该库不会自动从字节片中解析您的密钥。对于 ES256,我相信您需要提供 *ecdsa.PrivateKey 类型的密钥。从 v4 开始,只要它为该签名方法生成有效签名,它也将接受 crypto.Signer。

你可以试试这个代码示例

于 2019-10-06T13:27:58.337 回答
1

"exp": time.Now().Unix()+6000,发现问题,换成"exp": time.Now().Add(time.Minute * 20).Unix(),

于 2019-10-06T15:07:21.113 回答