-
Notifications
You must be signed in to change notification settings - Fork 1
/
google-jwt.go
83 lines (73 loc) · 1.74 KB
/
google-jwt.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v4"
"io/ioutil"
"net/http"
)
type GoogleClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
FirstName string `json:"given_name"`
LastName string `json:"family_name"`
jwt.RegisteredClaims
}
func getGooglePublicKey(keyID string) (string, error) {
resp, err := http.Get("https://www.googleapis.com/oauth2/v1/certs")
if err != nil {
return "", err
}
dat, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
myResp := map[string]string{}
err = json.Unmarshal(dat, &myResp)
if err != nil {
return "", err
}
key, ok := myResp[keyID]
if !ok {
return "", errors.New("key not found")
}
return key, nil
}
// ValidateGoogleJWT -
func ValidateGoogleJWT(tokenString string) (GoogleClaims, error) {
claimsStruct := GoogleClaims{}
token, err := jwt.ParseWithClaims(
tokenString,
&claimsStruct,
func(token *jwt.Token) (interface{}, error) {
pem, err := getGooglePublicKey(fmt.Sprintf("%s", token.Header["kid"]))
if err != nil {
return nil, err
}
key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(pem))
if err != nil {
return nil, err
}
return key, nil
},
)
if err != nil {
return GoogleClaims{}, err
}
claims, ok := token.Claims.(*GoogleClaims)
if !ok {
return GoogleClaims{}, errors.New("Invalid Google JWT")
}
if claims.Issuer != "accounts.google.com" && claims.Issuer != "https://accounts.google.com" {
return GoogleClaims{}, errors.New("iss is invalid")
}
return *claims, nil
}
func GetEmailFromGoogleJWT(tokenString string) (string, error) {
claims, err := ValidateGoogleJWT(tokenString)
if err != nil {
return "", err
}
return claims.Email, nil
}