Sobes.tech
Junior — Middle

What approach to authentication and authorization would you apply in your system?

sobes.tech AI

Answer from AI

For authentication and authorization in a Go system, I would use the approach with JWT (JSON Web Tokens). This allows securely transmitting user information between the client and server without the need to store sessions on the server.

Main steps:

  • During login, the user enters their data, the server verifies it, and generates a JWT with the necessary permissions (roles).
  • The token is sent to the client and stored, for example, in an HTTP-only cookie or localStorage.
  • For subsequent requests, the client sends the token in the Authorization header: Bearer <token>.
  • The server validates the token and makes access decisions based on the data in it.

Example of generating JWT using the github.com/dgrijalva/jwt-go library:

import (
    "time"
    "github.com/dgrijalva/jwt-go"
)

func GenerateJWT(userID string, role string) (string, error) {
    claims := jwt.MapClaims{}
    claims["user_id"] = userID
    claims["role"] = role
    claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString([]byte("your-secret-key"))
}

This approach is scalable, does not require session storage, and is well-suited for REST APIs.