在 Golang 中,我们可以使用中间件来验证 token。下面是一个示例:
package middleware
import (
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
if len(authHeader) != 2 || authHeader[0] != "Bearer" {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Invalid authorization header"))
return
}
tokenString := authHeader[1]
claims := &jwt.StandardClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
// Replace this with your own secret key or get it from a secure location.
return []byte("secret-key"), nil
})
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(err.Error()))
return
}
if !token.Valid {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Invalid token"))
return
}
next.ServeHTTP(w, r)
})
}
这个中间件会验证 Authorization 头部是否有一个合法的 Bearer token。如果没有或无效,将返回 401 Unauthorized 错误。注意,此处使用了 JWT 库进行解析和验证 token,你需要将 []byte("secret-key")
替换为你自己的密钥或从安全位置获取它。