1
1
package middleware
2
2
3
3
import (
4
- "github.com/golang-jwt/jwt/v4 "
4
+ "log "
5
5
"net/http"
6
6
"os"
7
7
"strings"
8
+
9
+ "github.com/golang-jwt/jwt/v4"
8
10
)
9
11
10
12
func VerifyJWT (next http.Handler ) http.Handler {
11
13
return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
14
+ // Skip JWT Verification for OPTIONS Requests
15
+ if r .Method == "OPTIONS" {
16
+ next .ServeHTTP (w , r )
17
+ return
18
+ }
19
+
12
20
// Get the token from the Authorization header
13
21
authHeader := r .Header .Get ("Authorization" )
14
22
if authHeader == "" {
@@ -17,7 +25,12 @@ func VerifyJWT(next http.Handler) http.Handler {
17
25
}
18
26
19
27
// Split the header to get the token
20
- tokenString := strings .Split (authHeader , " " )[1 ]
28
+ parts := strings .Split (authHeader , " " )
29
+ if len (parts ) != 2 || parts [0 ] != "Bearer" {
30
+ http .Error (w , "Invalid authorization header format" , http .StatusUnauthorized )
31
+ return
32
+ }
33
+ tokenString := parts [1 ]
21
34
22
35
// Retrieve the JWT secret from environment variables
23
36
jwtSecret := []byte (os .Getenv ("JWT_SECRET" ))
@@ -36,6 +49,7 @@ func VerifyJWT(next http.Handler) http.Handler {
36
49
37
50
if err != nil || ! token .Valid {
38
51
http .Error (w , "Invalid token" , http .StatusUnauthorized )
52
+ log .Printf ("Token parse error: %v" , err )
39
53
return
40
54
}
41
55
0 commit comments