-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
68 lines (52 loc) · 1.58 KB
/
middleware.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
package goliauth
import (
"fmt"
"net/http"
"strings"
)
// AuthenticateJWTMiddleware wraps AuthenticateJWTToken to provide middleware
// this is just an example to show how it can be used as a middleware
func AuthenticateJWTMiddleware(next http.Handler, secretKey string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := AuthenticateJWTToken(secretKey, r)
if err == nil {
next.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
})
}
// AuthenticateJWTToken is the main function to
// verify the JWT token from a request and it returns the claims
func AuthenticateJWTToken(secretKey string, req *http.Request) (map[string]interface{}, error) {
jwtToken, err := ExtractJWTToken(req)
if err != nil {
return nil, fmt.Errorf("Failed get JWT token")
}
claims, err := ParseJWT(jwtToken, secretKey)
if err != nil {
return nil, fmt.Errorf("Failed to parse token")
}
return claims, nil
}
// ExtractJWTToken extracts bearer token from Authorization header
func ExtractJWTToken(req *http.Request) (string, error) {
tokenString := req.Header.Get("Authorization")
if tokenString == "" {
return "", fmt.Errorf("Could not find token")
}
tokenString, err := stripTokenPrefix(tokenString)
if err != nil {
return "", err
}
return tokenString, nil
}
// Strips 'Token' or 'Bearer' prefix from token string
func stripTokenPrefix(tok string) (string, error) {
// split token to 2 parts
tokenParts := strings.Split(tok, " ")
if len(tokenParts) < 2 {
return tokenParts[0], nil
}
return tokenParts[1], nil
}