golang 後臺 蘋果一鍵登陸 sing in with apple

本文主要展現golang後臺編寫蘋果一鍵登陸的代碼.蘋果一鍵登陸的流程需自行去查看相關文檔前端

這是解析 identity_token的方法來驗證    若是是用code的話驗證 請去 https://blog.csdn.net/tptpppp/article/details/99288426 也是獲得蘋果的token而後解析出來驗證前端傳入的user,git

package main

import (
"crypto/rsa"
"fmt"
"github.com/astaxie/beego"
"github.com/dgrijalva/jwt-go"
"github.com/lestrrat-go/jwx/jwk"
"net/http"
)

// 解析token
func AppleParseToken(appleToken string) (*jwt.Token, error) {

set, err := jwk.FetchHTTP("https://appleid.apple.com/auth/keys", jwk.WithHTTPClient(http.DefaultClient))
if err != nil {
return nil, err
}
var isSuccess bool
var token *jwt.Token
  
// 蘋果這個祕鑰有點坑,返回了三個公鑰,要對每個公鑰都去進行解析,有一個成功了就行,全失敗纔算失敗,一開始項目只用了其中一個公鑰,運氣好每次都成功解析出來了,直到上生產環境才測出來這個bug
for _, key := range set.Keys{
pubKeyIface, _ := key.Materialize()
pubKey, ok := pubKeyIface.(*rsa.PublicKey)
if !ok {
beego.Error(fmt.Errorf(`expected RSA public key from %s`, "https://appleid.apple.com/auth/keys"))
continue
}

token, err = jwt.Parse(appleToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
beego.Error(fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]))
}
return pubKey, nil
})

if err != nil {
beego.Warning("Token Parse error:", err)
continue
}
if !token.Valid {
err = errors.New("token 無效")
beego.Warning("token 無效")
continue
}
isSuccess = true
break
}
if isSuccess {
return token, nil
}
return nil, errors.New("token 無效")
}


須要前端傳一個蘋果用戶惟一標識符user 以及identity_token, 將
identity_token 傳入函數解析出來,再用
claims := token.Claims.(jwt.MapClaims)
sub := claims["sub"].(string)

而後用sub跟user比較一下不相等的話就表明前端傳的user=有問題,相等的話就存下user惟一標識符進行註冊就能夠了.
相關文章
相關標籤/搜索