go语言中实现jwt认证的核心是生成和验证token,使用github.com/golang-jwt/jwt/v5库可完成该流程;首先定义包含用户信息和标准声明的claims结构,通过jwt.newwithclaims结合hmac-sha256算法生成签名token,有效期通常设为24小时;在验证时,从请求头authorization: bearer <token>中提取token,利用jwt.parsewithclaims解析并校验签名和过期时间;可通过中间件封装验证逻辑,保护特定路由,确保只有合法token才能访问受保护接口;实际应用中需将密钥存于环境变量、避免硬编码,设置合理过期时间并启用https传输以提升安全性,完整流程包括登录生成token、接口验证、中间件拦截和安全防护措施,适用于中小型项目身份认证需求。

在 Go 语言(Golang)中实现 JWT(JSON Web Token)认证,主要涉及两个核心流程:生成 Token 和 验证 Token。JWT 常用于用户登录后的身份认证,比如 Web API 的权限控制。
下面是一个完整的、实用的 JWT 实现流程,使用广泛使用的第三方库
github.com/golang-jwt/jwt/v5
golang-jwt/jwt
go get github.com/golang-jwt/jwt/v5
JWT 通常使用 HMAC、RSA 等算法签名。这里以对称加密的 HMAC-SHA256 为例,使用一个密钥字符串。
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
)
// 密钥,应保存在环境变量中
var jwtKey = []byte("your-secret-key-change-in-production")
// 定义用户声明(Claims)
type Claims struct {
UserID uint `json:"user_id"`
Email string `json:"email"`
jwt.RegisteredClaims
}RegisteredClaims 包含标准字段如 ExpiresAt、Issuer、Subject 等。
当用户登录成功后,生成一个 Token 并返回给客户端。
func generateToken(userID uint, email string) (string, error) {
expirationTime := time.Now().Add(24 * time.Hour) // 24小时有效期
claims := &Claims{
UserID: userID,
Email: email,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "your-app-name",
Subject: fmt.Sprintf("user-%d", userID),
},
}
// 创建 token 对象
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// 签名并生成字符串
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", err
}
return tokenString, nil
}在受保护的接口中,从请求头(通常是
Authorization: Bearer <token>
func validateToken(tokenString string) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
// 验证签名算法是否正确
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return jwtKey, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return claims, nil
}你可以写一个中间件来保护某些路由。
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header missing", http.StatusUnauthorized)
return
}
// Bearer <token>
var tokenString string
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
tokenString = authHeader[7:]
} else {
http.Error(w, "Invalid authorization format", http.StatusUnauthorized)
return
}
claims, err := validateToken(tokenString)
if err != nil {
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
return
}
// 可将用户信息存入上下文,供后续处理使用
// 这里简单打印
fmt.Printf("Authenticated user: %s (ID: %d)\n", claims.Email, claims.UserID)
next(w, r)
}
}func loginHandler(w http.ResponseWriter, r *http.Request) {
// 模拟登录验证(实际应查数据库)
email := r.FormValue("email")
password := r.FormValue("password")
// 简单模拟验证
if email == "user@example.com" && password == "pass123" {
token, err := generateToken(123, email)
if err != nil {
http.Error(w, "Failed to generate token", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"token": "%s"}`, token)
return
}
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
}
func protectedHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("This is a protected route!"))
}
func main() {
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/protected", authMiddleware(protectedHandler))
fmt.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}curl -X POST http://localhost:8080/login \ -d "email=user@example.com" \ -d "password=pass123"
返回:
{"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx"}curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx" \ http://localhost:8080/protected
jwtKey
jti
Golang 实现 JWT 认证的关键步骤:
Claims
jwt.NewWithClaims
jwt.ParseWithClaims
Authorization
这套流程足够用于中小型项目。如需更高安全级别,可升级为 RSA 非对称加密或集成 OAuth2。
基本上就这些,不复杂但容易忽略细节。
以上就是Golang实现JWT认证怎么做 生成和验证Token完整流程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号