/
verify.go
86 lines (69 loc) · 2.11 KB
/
verify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package fire_verify_auth
import (
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"strings"
jwtGo "github.com/golang-jwt/jwt/v4"
)
const (
clientCertURL = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
)
func VerifyIDToken(idToken string, projectID string) (map[string]interface{}, error) {
keys, err := fetchPublicKeys()
if err != nil {
return nil, err
}
parsedToken, parseErr := jwtGo.Parse(idToken, func(token *jwtGo.Token) (interface{}, error) {
if _, ok := token.Method.(*jwtGo.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
kid := token.Header["kid"]
rsaPublicKey := convertKey(string(*keys[kid.(string)]))
return rsaPublicKey, nil
})
if parseErr != nil {
return nil, parseErr
}
if parsedToken == nil {
return nil, errors.New("nil parsed token")
}
errMessage := ""
claims, ok := parsedToken.Claims.(jwtGo.MapClaims)
if ok && parsedToken.Valid {
if claims["aud"].(string) != projectID {
errMessage = "Firebase Auth ID token has incorrect 'aud' claim: " + claims["aud"].(string)
} else if claims["iss"].(string) != "https://securetoken.google.com/"+projectID {
errMessage = "Firebase Auth ID token has incorrect 'iss' claim"
} else if claims["sub"].(string) == "" || len(claims["sub"].(string)) > 128 {
errMessage = "Firebase Auth ID token has invalid 'sub' claim"
}
}
if errMessage != "" {
return nil, errors.New(errMessage)
}
return claims, nil
}
func fetchPublicKeys() (map[string]*json.RawMessage, error) {
resp, err := http.Get(clientCertURL)
if err != nil {
return nil, err
}
var objMap map[string]*json.RawMessage
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&objMap)
return objMap, err
}
func convertKey(key string) interface{} {
certPEM := key
certPEM = strings.Replace(certPEM, "\\n", "\n", -1)
certPEM = strings.Replace(certPEM, "\"", "", -1)
block, _ := pem.Decode([]byte(certPEM))
cert, _ := x509.ParseCertificate(block.Bytes)
rsaPublicKey := cert.PublicKey.(*rsa.PublicKey)
return rsaPublicKey
}