-
Notifications
You must be signed in to change notification settings - Fork 4
/
verify.go
80 lines (62 loc) · 1.95 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
package firebase
import (
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
"strings"
"gopkg.in/dgrijalva/jwt-go.v3"
)
const (
clientCertURL = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
)
func VerifyIDToken(idToken string, googleProjectID string) (string, error) {
keys, err := fetchPublicKeys()
if err != nil {
return "", err
}
parsedToken, err := jwt.Parse(idToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
kid := token.Header["kid"]
certPEM := string(*keys[kid.(string)])
certPEM = strings.Replace(certPEM, "\\n", "\n", -1)
certPEM = strings.Replace(certPEM, "\"", "", -1)
block, _ := pem.Decode([]byte(certPEM))
var cert *x509.Certificate
cert, _ = x509.ParseCertificate(block.Bytes)
rsaPublicKey := cert.PublicKey.(*rsa.PublicKey)
return rsaPublicKey, nil
})
if err != nil {
return "", err
}
errMessage := ""
claims := parsedToken.Claims.(jwt.MapClaims)
if claims["aud"].(string) != googleProjectID {
errMessage = "Firebase Auth ID token has incorrect 'aud' claim: " + claims["aud"].(string)
} else if claims["iss"].(string) != "https://securetoken.google.com/"+googleProjectID {
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 "", errors.New(errMessage)
}
return string(claims["sub"].(string)), nil
}
func fetchPublicKeys() (map[string]*json.RawMessage, error) {
resp, err := http.Get(clientCertURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var objmap map[string]*json.RawMessage
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&objmap)
return objmap, err
}