-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_header_jwt.go
52 lines (42 loc) · 1.22 KB
/
auth_header_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
package rest
import (
"fmt"
"github.com/golang-jwt/jwt"
"net/http"
)
func AuthenticationJwt(headerName, secret string, userCondition func(claims map[string]interface{}) error) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Header[headerName] == nil {
http.Error(w, "Can not find token in header", http.StatusForbidden)
return
}
token, _ := jwt.Parse(r.Header[headerName][0], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("[ERROR] There was an error in parsing")
}
return []byte(secret), nil
})
if token == nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
if !token.Valid {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
w.Write([]byte("couldn't parse claims"))
w.WriteHeader(http.StatusUnauthorized)
return
}
if err := userCondition(claims); err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}