-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-jwt.go
111 lines (97 loc) · 2.52 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package googlejwt
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jws"
cache "github.com/patrickmn/go-cache"
)
type AuthorizationHandler interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
}
type AuthorizationMiddleware struct {
WrappedHandler AuthorizationHandler
Cache *cache.Cache
Domain string
}
func (h AuthorizationMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t := authorized(r.Header.Get("Authorization"), h.Cache, h.Domain)
if !t {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return
}
h.WrappedHandler.ServeHTTP(w, r)
}
func Init(handler AuthorizationHandler, domain string) AuthorizationMiddleware {
ch := cache.New(60*time.Minute, 120*time.Minute)
return AuthorizationMiddleware{
WrappedHandler: handler,
Cache: ch,
Domain: domain,
}
}
func authorized(authHeader string, c *cache.Cache, domain string) bool {
tokenString := strings.Replace(authHeader, "Bearer ", "", -1)
token, err := jws.ParseString(tokenString)
if err != nil {
log.Printf("Failed to parse with error: %s", err)
return false
}
key, _ := token.Signatures()[0].ProtectedHeaders().Get("kid")
keyID := fmt.Sprintf("%v", key)
var dat map[string]interface{}
if err := json.Unmarshal(token.Payload(), &dat); err != nil {
log.Printf("Failed to parse Json, with error: %s", err)
return false
}
if domain != "" && dat["hd"] != domain {
return false
}
keys, err := findKeys(c, keyID)
if err != nil {
log.Printf("Failed to lookup key: %s", err)
return false
}
payload, err := jws.VerifyWithJWK([]byte(tokenString), keys[0])
if err != nil {
log.Printf("Failed to verify message: %s", err)
return false
}
return payload != nil
}
func findKeys(c *cache.Cache, keyID string) ([]jwk.Key, error) {
url := "https://www.googleapis.com/oauth2/v3/certs"
var keys []jwk.Key
loop := true
count := 0
for loop {
fetchedKeys, found := c.Get("fetchedKeys")
var set *jwk.Set
var err error
if found {
set = fetchedKeys.(*jwk.Set)
} else {
set, err = jwk.Fetch(url)
if err != nil {
log.Printf("Failed to parse JWK: %s", err)
return keys, err
}
c.Set("fetchedKeys", set, cache.NoExpiration)
}
keys = set.LookupKeyID(keyID)
if len(keys) > 0 {
return keys, nil
} else if count > 1 {
return nil, errors.New("Can not find the key")
}
c.Delete("fetchedKeys")
count++
}
return nil, errors.New("Can not find the key")
}