JWT (JSON Web Token) is a stateless, independent, compact and independent information format used to pass claims (claims) between network application environments. The following is the basic process for JWT to authenticate:
1. User login
The user logs into the system through the user name and password, and the system verifies the user's identity.
2. Generate JWT token
After the system successfully verifies the user's identity, a JWT token is generated. A JWT token usually contains the following parts:
Header (header): Contains the type of the token (usually JWT) and the signature algorithm used (such as HMAC-SHA256).
Payload: Contains claims, which can be user ID, role, expiration time, etc.
Signature: Used to verify the integrity and authenticity of JWT.
3. Return the JWT token
The system returns the generated JWT token to the client (usually a browser or mobile application).
4. Client storage JWT tokens
After the client receives the JWT token, it will usually store it in local storage (such aslocalStorage
orsessionStorage
) or in a cookie.
5. The client sends a request
In subsequent requests, the client places the JWT token in the HTTP request headerAuthorization
In the field, the format is usuallyBearer <token>
。
6. Server-side verification JWT token
After the server receives the request,Authorization
Extract the JWT token from the request header and verify it:
Verify signature: Verify that the signature of the JWT is valid using the same key as when generating the JWT.
Verification expiration time: Check whether the expiration time of the JWT has expired.
Verify other statements: Verify other statements as needed, such as user roles, permissions, etc.
7. Process the request
If the JWT token verification passes, the server processes the request and returns a response. If verification fails, an error response is returned (such as 401 Unauthorized).
Sample code
Generate JWT token (server side)
package main import ( "fmt" "time" "/golang-jwt/jwt" ) // Custom Claimstype CustomClaims struct { UserID string `json:"user_id"` Role string `json:"role"` } func main() { // Custom Claims claims := CustomClaims{ UserID: "12345", Role: "admin", StandardClaims: { ExpiresAt: ().Add(24 * ).Unix(), Issuer: "myapp", }, } // Key jwtSecret := "mysecretkey" // Create a JWT token token := (jwt.SigningMethodHS256, claims) // Sign with a key and generate a JWT token in string form tokenString, err := ([]byte(jwtSecret)) if err != nil { ("Creating token failed:", err) return } ("Generated JWT Token:", tokenString) }
Verify JWT token (server side)
package main import ( "fmt" "net/http" "strings" "/golang-jwt/jwt" ) // Custom Claimstype CustomClaims struct { UserID string `json:"user_id"` Role string `json:"role"` } func handler(w , r *) { // Get the Authorization request header authHeader := ("Authorization") // Check whether the Authorization request header exists if authHeader == "" { (w, "Missing Authorization header", ) return } // Extract JWT token tokenString := (authHeader, "Bearer ") // Verify the JWT token token, err := (tokenString, &CustomClaims{}, func(token *) (interface{}, error) { // Provide a signature key return []byte("mysecretkey"), nil }) if err != nil { (w, "Invalid token", ) return } if ! { (w, "Invalid token", ) return } // Process the request (w, "Hello, World!") } func main() { ("/api/data", handler) (":8080", nil) }
The method of verifying jwt token can be defined as middleware, registered in gin through the Use method, and applied to all routes. Gin's middleware is called in the request processing process, and can preprocess the request, modify the request or respond, and even terminate the request processing. Middleware is very commonly used in Gin and can be used to implement functions such as authentication, logging, request restriction, etc.
Sample code:
package main import ( "/gin-gonic/gin" "/golang-jwt/jwt" "strings" ) // Custom Claimstype CustomClaims struct { UserID string `json:"user_id"` Role string `json:"role"` } // Auth returns a Gin middleware functionfunc Auth() { return func(c *) { // Get the Authorization request header authHeader := ("Authorization") // Check whether the Authorization request header exists if authHeader == "" { (401, {"error": "Missing Authorization header"}) () return } // Extract JWT token tokenString := (authHeader, "Bearer ") // Verify the JWT token token, err := (tokenString, &CustomClaims{}, func(token *) (interface{}, error) { // Provide a signature key return []byte("mysecretkey"), nil }) if err != nil { (401, {"error": "Invalid token"}) () return } if ! { (401, {"error": "Invalid token"}) () return } // If the verification is passed, continue to process the request () } } func main() { r := () // Use Auth middleware (Auth()) ("/api/data", func(c *) { (200, {"message": "Hello, World!"}) }) (":8080") }
This is the end of this article about the implementation process of golang jwt authentication. For more related golang jwt authentication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!