Senior
How does the standard JWT authorization scheme generally work?
sobes.tech AI
Answer from AI
The standard JWT (JSON Web Token) authentication scheme usually involves the following steps:
- The user sends their credentials (login and password) to the server.
- The server verifies the data, and if correct, creates a JWT that contains payload data (e.g., user ID, roles) and signs it with a secret key.
- The JWT is returned to the client, which stores it (e.g., in localStorage or a cookie).
- For subsequent requests, the client sends the JWT in the Authorization header (usually "Bearer <token>").
- The server verifies the token's signature and, if valid, extracts user information from it and grants access to protected resources.
In Go, this is often implemented using JWT libraries, such as github.com/dgrijalva/jwt-go.
Example of creating a token:
import (
"github.com/dgrijalva/jwt-go"
"time"
)
func GenerateJWT(userID string, secret []byte) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"exp": time.Now().Add(time.Hour * 72).Unix(),
})
return token.SignedString(secret)
}
Thus, JWT allows secure transmission of user information without the need to store a session on the server.