This commit is contained in:
wangjianhong
2025-07-23 17:30:33 +08:00
commit 5e4e272b3a
875 changed files with 362355 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package middleware
import (
"net/http"
"github.com/dgrijalva/jwt-go"
)
// JWTMiddleware 实现JWT认证中间件
func JWTMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if tokenString == "" {
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("your-secret-key"), nil
})
if err != nil || !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}