用go gin 写一个jwt 例子
时间: 2024-06-12 14:05:51 浏览: 11
以下是一个使用go gin和jwt的示例:
```go
package main
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/dgrijalva/jwt-go"
)
var jwtKey = []byte("my_secret_key")
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
func main() {
router := gin.Default()
router.POST("/login", login)
router.GET("/welcome", authMiddleware(), welcome)
router.Run(":8080")
}
func login(c *gin.Context) {
var user struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
if user.Username != "myusername" || user.Password != "mypassword" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
return
}
expirationTime := time.Now().Add(5 * time.Minute)
claims := &Claims{
Username: user.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not generate token"})
return
}
c.JSON(http.StatusOK, gin.H{"token": tokenString})
}
func welcome(c *gin.Context) {
claims := c.MustGet("claims").(*Claims)
c.JSON(http.StatusOK, gin.H{"message": "Welcome " + claims.Username + "!"})
}
func authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
return
}
tokenString := authHeader[len("Bearer "):]
token, claims, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.NewValidationError("Unexpected signing method", jwt.SigningMethodHS256)
}
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token signature"})
return
}
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid token"})
return
}
if !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
c.Set("claims", claims)
c.Next()
}
}
```
在这个例子中,我们使用`jwt-go`库来创建和验证JWT令牌。我们使用`gin`框架来创建HTTP路由和中间件。
在`/login`路由中,我们检查传递的用户名和密码是否正确。如果正确,我们使用用户名创建一个JWT声明,并设置过期时间为5分钟。然后,我们使用声明创建一个JWT令牌,并将其签名为字符串。最后,我们将令牌返回给客户端。
在`/welcome`路由中,我们使用`authMiddleware`中间件来验证JWT令牌。如果令牌验证通过,我们从声明中提取用户名并返回欢迎消息。如果令牌验证失败,我们返回错误响应。如果请求不包含Authorization头,我们也返回错误响应。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)