This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
85 lines (71 loc) · 2.36 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
78
79
80
81
82
83
84
85
package main
import (
"github.com/go-jose/go-jose/v3/jwt"
log "github.com/sirupsen/logrus"
"net/http"
"strings"
)
type TokenClaims struct {
jwt.Claims
}
func jwtAuth(next func(w http.ResponseWriter, r *http.Request, claims *TokenClaims)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
writeErr(w, http.StatusBadRequest, "jwtAuth, authorization header not set")
return
}
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) != 2 {
writeErr(w, http.StatusBadRequest, "jwtAuth, could not split token: %v", bearerToken)
return
}
tok, err := jwt.ParseSigned(bearerToken[1])
if err != nil {
writeErr(w, http.StatusBadRequest, "jwtAuth, could not parse token: %v", bearerToken[1])
return
}
claims := &TokenClaims{}
if tok.Headers[0].Algorithm == "HS256" {
err = tok.Claims(jwtKey, claims)
} else {
writeErr(w, http.StatusUnauthorized, "jwtAuth, unknown algorithm: %v", tok.Headers[0].Algorithm)
return
}
if err != nil {
writeErr(w, http.StatusUnauthorized, "jwtAuth, could not parse claims: %v", bearerToken[1])
return
}
if claims == nil {
writeErr(w, http.StatusBadRequest, "jwtAuth, claims are empty")
return
}
if claims.Expiry != nil && !claims.Expiry.Time().After(timeNow()) {
writeErr(w, http.StatusBadRequest, "jwtAuth, expired: %v", claims.Expiry.Time())
return
}
next(w, r, claims)
}
}
func jwtAuthAdmin(next func(w http.ResponseWriter, r *http.Request, email string), emails []string) func(http.ResponseWriter, *http.Request, *TokenClaims) {
return func(w http.ResponseWriter, r *http.Request, claims *TokenClaims) {
for _, email := range emails {
if claims.Subject == email {
log.Printf("Authenticated admin %s\n", email)
next(w, r, email)
return
}
}
writeErr(w, http.StatusBadRequest, "ERR-01,jwtAuthAdmin error: %v != %v", claims.Subject, emails)
}
}
func jwtAuthServer(next func(w http.ResponseWriter, r *http.Request)) func(http.ResponseWriter, *http.Request, *TokenClaims) {
return func(w http.ResponseWriter, r *http.Request, claims *TokenClaims) {
if claims.Subject == "ffs-server" {
log.Printf("Authenticated server %s\n")
next(w, r)
return
}
writeErr(w, http.StatusBadRequest, "ERR-01,jwtAuthAdmin error: %v", claims.Subject)
}
}