-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
68 lines (56 loc) · 2 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 main
import (
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go" // Import for JWT package (use the appropriate import path)
)
// JWTMiddleware encapsulates the secret key and validation logic.
type jWTMiddleware struct {
secretKey []byte
}
func (calc *calculator) logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
ip = r.RemoteAddr
proto = r.Proto
method = r.Method
uri = r.URL.RequestURI()
)
calc.logger.Info("received request", "ip", ip, "proto", proto, "method", method, "uri", uri)
next.ServeHTTP(w, r)
})
}
// JWT Middleware to check Authorization header
func (calc *calculator) authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the Authorization header
authHeader := r.Header.Get("Authorization")
// If the header is missing or does not contain "Bearer <token>"
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
http.Error(w, "Unauthorized: Missing or invalid token", http.StatusUnauthorized)
return
}
// Extract the token part from the Authorization header
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
// Validate the token
token, err := validateToken(calc.jWTMiddleware.secretKey, tokenString)
if err != nil || !token.Valid {
http.Error(w, "Unauthorized: Invalid or expired token", http.StatusUnauthorized)
return
}
// If valid, proceed to the next handler
next.ServeHTTP(w, r)
})
}
// ValidateToken parses and validates the JWT token using the secret key.
func validateToken(secretKey []byte, tokenString string) (*jwt.Token, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Ensure the signing method is HMAC.
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secretKey, nil
})
return token, err
}