-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
jwt.go
77 lines (59 loc) · 1.32 KB
/
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
package auth
import (
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dosco/graphjin/serv/internal/auth/provider"
)
const (
authHeader = "Authorization"
)
func JwtHandler(ac *Auth, next http.Handler) (http.HandlerFunc, error) {
jwtProvider, err := provider.NewProvider(ac.JWT)
if err != nil {
return nil, err
}
cookie := ac.Cookie
return func(w http.ResponseWriter, r *http.Request) {
var tok string
if cookie != "" {
ck, err := r.Cookie(cookie)
if err != nil {
next.ServeHTTP(w, r)
return
}
tok = ck.Value
} else {
ah := r.Header.Get(authHeader)
if len(ah) < 10 {
next.ServeHTTP(w, r)
return
}
tok = ah[7:]
}
keyFunc := jwtProvider.KeyFunc()
token, err := jwt.ParseWithClaims(tok, jwt.MapClaims{}, keyFunc) //jwt.MapClaims is already passed by reference
if err != nil {
next.ServeHTTP(w, r)
return
}
if claims, ok := token.Claims.(jwt.MapClaims); ok {
ctx := r.Context()
if !jwtProvider.VerifyAudience(claims) {
next.ServeHTTP(w, r)
return
}
if !jwtProvider.VerifyIssuer(claims) {
next.ServeHTTP(w, r)
return
}
ctx, err = jwtProvider.SetContextValues(ctx, claims)
if err != nil {
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r.WithContext(ctx))
return
}
next.ServeHTTP(w, r)
}, nil
}