目录
1、代码实现样例:
2、postman调用,获取登陆后的token:
1、代码实现样例:
package mainimport ("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.Usernameclaims["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")
}