因为PC端的业务要做apple登录,需要获取用户的appleid,调用苹果API的时候要生成jwt格式的client_secret,go语言的实现如下:
1 创建client_id,授权文件等,具体创建方式参考:https://www.icrazycode.com/archives/1257
2 将下载的 p8
证书文件转 pkcs8 pem
openssl pkcs8 -nocrypt -in AuthKey_U7BAXSKVQ7.p8 -out SubscriptionKey.pem
openssl pkcs8 -topk8 -inform PEM -outform DER -in SubscriptionKey.pem -nocrypt > AuthKey_U7BAXSKVQ7.pem
3 代码如下
package appleid
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
const APPLE_AUTH_TOKEN_URL = "https://appleid.apple.com/auth/token"
func GenerateClientSecret(clientID, teamID, keyID, authKeyFile string) (string, error) {
appleUser := AppleUser{}
appleUser.Subject = clientID
appleUser.Issuer = teamID
appleUser.IssuedAt = jwt.NewNumericDate(time.Now())
appleUser.NotBefore = jwt.NewNumericDate(time.Now())
appleUser.ExpiresAt = jwt.NewNumericDate(time.Now().Add(24 * time.Hour))
appleUser.Audience = []string{"https://appleid.apple.com"}
claims := jwt.NewWithClaims(jwt.SigningMethodES256, appleUser)
claims.Header["kid"] = keyID
path, _ := os.Getwd()
authFile := filepath.Join(path, "config", authKeyFile)//文件的存放目录
privatePem, _ := os.ReadFile(authFile)
ecdsaKey, _ := x509.ParsePKCS8PrivateKey(privatePem)
signString, err := claims.SignedString(ecdsaKey)
if err != nil {
return "", err
}
return signString, nil
}
文章评论