/
jwt_middlewares.go
75 lines (64 loc) · 1.57 KB
/
jwt_middlewares.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
package auth
import (
"fmt"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
)
func RequireTokenAuthentication(w http.ResponseWriter, req *http.Request,
next http.HandlerFunc) {
// Preflight handling
if req.Method == "OPTIONS" {
return
}
authBackend, err := InitJwtAuthBackend()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
token, err := jwt.ParseFromRequest(
req,
func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf(
"Unexpected signing method: %v",
token.Header["alg"],
)
} else {
return authBackend.PublicKey, nil
}
},
)
if err == nil &&
token.Valid &&
!authBackend.IsTerminated(req.Header.Get("Authorization")) {
next(w, req)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
func ValidateTokenAuthentication(w http.ResponseWriter, req *http.Request,
next http.HandlerFunc) {
w.Header().Add("Access-Control-Allow-Origin", "*")
authBackend, err := InitJwtAuthBackend()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
token, err := jwt.ParseFromRequest(
req,
func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf(
"Unexpected signing method: %v",
token.Header["alg"],
)
} else {
return authBackend.PublicKey, nil
}
},
)
if err == nil && token.Valid && !authBackend.IsTerminated(
req.Header.Get("Authorization")) {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}