Golang engineering components: middleware programming and jwt authentication of high-performance web framework gin

As a fast and efficient programming language, Golang can improve performance and efficiency when developing web applications. Gin is a high-performance web framework, and its middleware programming and jwt authentication functions can help developers develop applications more conveniently.

1. Middleware programming

In gin, a middleware is a pluggable modular component, similar to an interceptor or filter. By using middleware, we can implement functions such as logging, authorization verification, and current limiting.

  1. middleware definition

In the gin framework, middleware is implemented by defining functions:

func MyMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // TODO: 中间件逻辑
    }
}

The above code defines a middleware named MyMiddleware and returns a function type. This function type accepts a parameter c *gin.Context, representing the HTTP request context object. Arbitrary logic code can be written inside this function.

  1. middleware registration

When the application starts, the middleware needs to be registered with the corresponding route:

r := gin.Default()
r.Use(MyMiddleware())

The above code registers MyMiddleware to the default route, indicating that all HTTP requests passing through the route will be processed by the middleware.

2. JWT authentication

JWT (Json Web Token) is a lightweight, JSON-based secure transmission protocol, usually used for identity authentication and information transmission. In the gin framework, we can use JWT to implement identity authentication.

  1. JWT generation

In the application, the user's identity information needs to be encoded into a JWT and returned to the client:

func GenerateToken(user *models.User) (string, error) {
    claims := jwt.MapClaims{
        "id":    user.ID,
        "email": user.Email,
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

    return token.SignedString([]byte("secret"))
}

The above code defines the GenerateToken function, accepts a User type parameter, and encodes its ID and Email as payload into a JWT. Finally, use the HS256 algorithm to sign and return the JWT string.

  1. JWT verification

In the route that requires authentication, we need to obtain the JWT by parsing the Authorization field of the HTTP request header and verify it:

func AuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        authHeader := c.GetHeader("Authorization")
        if len(authHeader) == 0 {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
            c.Abort()
            return
        }

        tokenStr := strings.Replace(authHeader, "Bearer ", "", 1)
        token, err := jwt.Parse(tokenStr, 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 []byte("secret"), nil
        })

        if err != nil || !token.Valid {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"})
            c.Abort()
            return
        }

        claims, ok := token.Claims.(jwt.MapClaims)
        if !ok {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
            c.Abort()
            return
        }

        userID := int(claims["id"].(float64))
        
        // TODO: 处理逻辑
    }
}

The above code defines a middleware called AuthMiddleware, which is used to verify the JWT and obtain the user ID information in it. If the JWT is invalid or expired, a corresponding error message will be returned.

Summarize:

The above is a 3,000-word article about golang engineering components: high-performance web framework gin middleware programming and jwt authentication. I hope it will be helpful to everyone. When developing web applications, middleware and identity authentication are essential parts, which can make developers develop applications more conveniently and ensure the security and stability of the programs.

Guess you like

Origin blog.csdn.net/SMILY12138/article/details/130885140