Senior
Tell me about tokens: what types are there, how they are structured internally, and what they are used for. How does authentication differ from authorization?
sobes.tech AI
Answer from AI
Tokens are objects used to transmit information about a user or session between a client and a server, often for authentication and authorization purposes.
Types of tokens:
- JWT (JSON Web Token): contains three parts — header, payload, and signature. Used to transmit information in encrypted or signed form.
- Opaque tokens: non-transparent tokens that do not carry information themselves but are used as keys to retrieve data on the server.
- Refresh tokens: used to obtain new access tokens without re-authenticating.
Internal structure:
- In JWT, for example, the payload contains claims about the user and expiration times.
- The signature ensures the integrity and authenticity of the token.
Purpose:
- Tokens allow the server to verify the user's identity without needing to store session state.
- They provide scalability and security in distributed systems.
Authentication vs Authorization:
- Authentication — the process of verifying the user's identity (e.g., entering login and password).
- Authorization — the process of determining what actions or resources are accessible to the authenticated user.
Example of using JWT in Go:
import (
"github.com/dgrijalva/jwt-go"
"time"
)
func GenerateJWT(secret []byte, userID string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"exp": time.Now().Add(time.Hour * 72).Unix(),
})
return token.SignedString(secret)
}