目录
1、代码实现样例:
package main
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var (
// 密钥,用于签署 JWT 令牌
signingKey = []byte("secret")
)
// 用户信息
type User struct {
Username string `json:"username"`
Password string `json:"-"`
}
// 模拟用户数据
var users = map[string]User{
"user1": {"user1", "password1"},
"user2": {"user2", "password2"},
}
// 登录处理程序
func LoginHandler(c *gin.Context) {
var credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.BindJSON(&credentials); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
// 检查用户名和密码
user, ok := users[credentials.Username]
if !ok || user.Password != credentials.Password {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password"})
return
}
// 创建 JWT 令牌
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["username"] = user.Username
claims["exp"] = time.Now().Add(time.Hour * 24).Unix() // 令牌过期时间为24小时
// 签名令牌
tokenString, err := token.SignedString(signingKey)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
return
}
// 返回令牌给客户端
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}
func main() {
r := gin.Default()
// 登录路由
r.POST("/login", auth2.LoginHandler)
// 启动服务
r.Run(":8080")
}