Home > Article > Backend Development > Use JWT in Go language to implement simple and secure user authentication
With the rapid development of network technology, more and more websites and applications need to implement user authentication functions. However, traditional username and password authentication methods have security risks because they are usually stored in the database. Once the database is attacked, user information will be leaked. In order to solve this problem, JWT (JSON Web Token) came into being. JWT is an open standard (RFC 7519) that defines a simple, self-contained way to transmit information that can be verified and trusted. This article will introduce how to use JWT in Go language to implement simple and secure user authentication.
JWT working principle
Before introducing how to use JWT in Go language, let’s first understand how JWT works. JWT consists of three parts:
The token generated by JWT can be passed through HTTP header information or URL parameters. When the client requests the server, the server will check the JWT token in the request header or URL parameters. If the token is valid, it will return the data requested by the client. If the token is invalid, an error message is returned.
In actual applications, the server should set a validity period when generating JWT. After expiration, the client needs to obtain a new JWT token again.
Using JWT in Go language
The JWT function can be quickly and simply implemented in Go language by using a third-party library. This article recommends using the jwt-go library, which supports the generation and verification of JWT and has the advantages of type safety and high performance.
Install jwt-go library
Enter the following command in the terminal. You can use the go get command to install the jwt-go library.
go get github.com/dgrijalva/jwt-go
Generate JWT
In Go language, generating JWT can be achieved through the following code:
package main import ( "fmt" "time" "github.com/dgrijalva/jwt-go" ) func main() { // 创建JWT头信息 token := jwt.New(jwt.SigningMethodHS256) // 设置有效期 token.Claims = jwt.MapClaims{ "exp": time.Now().Add(time.Hour * 72).Unix(), "iat": time.Now().Unix(), "sub": "1234567890", } // 对生成的JWT令牌进行签名 signedToken, err := token.SignedString([]byte("secret-key")) if err != nil { fmt.Println(err) return } fmt.Println(signedToken) }
In the code, use the jwt.New() function to create the JWT header information , set the validity period and the transmitted information (in the example, a field named sub is transmitted), and then use the SignedString() function to sign the JWT token.
Verify JWT
In Go language, verifying JWT can be implemented using the following code:
package main import ( "fmt" "time" "github.com/dgrijalva/jwt-go" ) func main() { // 待验证的JWT令牌 tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTAzMDAzMTAsImlhdCI6MTYxMDgwNTExMCwic3ViIjoiMTIzNDU2Nzg5MCJ9.5AtrChvChVuWI3TkazGt1mDhbscT8-Qal5U6Qc4dqhc" // 解析JWT头信息 token, err := jwt.Parse(tokenString, 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-key"), nil }) if err != nil { fmt.Println(err) return } // 验证JWT有效期 if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { expirationTime := time.Unix(int64(claims["exp"].(float64)), 0) if expirationTime.Before(time.Now()) { fmt.Println("JWT has expired") } else { fmt.Println("JWT is valid") } } else { fmt.Println("JWT is not valid") } }
In the code, use the jwt.Parse() function to parse the JWT to be verified The token is then verified using the passed signing key. During verification, first use the Claims() function to obtain the validity time in the JWT, and then compare it with the current time. If the token has expired, an error message is returned.
Summary
As a safe and simple authentication method, JWT is widely used in Web development. This article introduces how to use the jwt-go library in the Go language to quickly and simply implement the JWT function. JWT can be used not only for user authentication, but also for data transmission, API authentication and other scenarios. In practical applications, we should pay attention to the validity period of JWT and the security protection of the signing key.
The above is the detailed content of Use JWT in Go language to implement simple and secure user authentication. For more information, please follow other related articles on the PHP Chinese website!