Autorización y autenticación en Go (Golang): JWT, OAuth2 y sesiones

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Autorización y autenticación en Go (Golang)



La seguridad de las aplicaciones web en Go comienza con la implementación correcta de los mecanismos de autenticación (verificación de "quién eres") y autorización (verificación de "qué puedes hacer"). En este artículo analizaremos tres enfoques principales: JWT (JSON Web Tokens), OAuth2 y la autenticación por sesiones. Cada uno tiene sus propios casos de uso, ventajas y desventajas.



1. Autenticación con JWT (JSON Web Token)



JWT es una forma compacta y autónoma de transmitir información entre partes en forma de objeto JSON. En Go, la biblioteca más utilizada para trabajar con JWT es github.com/golang-jwt/jwt/v5.



Instalación:

go get github.com/golang-jwt/jwt/v5


Ejemplo de creación y verificación de JWT:

package main

import (\t"fmt"\t"time"\t"github.com/golang-jwt/jwt/v5")

var jwtSecret = []byte("my_secret_key")

// Creación del tokenfunc createToken(userID string) (string, error) {\tclaims := jwt.MapClaims{\t\t"user_id": userID,\t\t"exp": time.Now().Add(24 * time.Hour).Unix(),\t}\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\treturn token.SignedString(jwtSecret)}

// Verificación del tokenfunc validateToken(tokenString string) (string, error) {\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\t\t\treturn nil, fmt.Errorf("método de firma no válido")\t\t}\t\treturn jwtSecret, nil\t})

\tif err != nil {\t\treturn "", err\t}

\tif claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {\t\treturn claims["user_id"].(string), nil\t}\treturn "", fmt.Errorf("token no válido")}

func main() {\ttoken, _ := createToken("user123")\tfmt.Println("Token:", token)

\tuserID, err := validateToken(token)\tif err != nil {\t\tfmt.Println("Error:", err)\t} else {\t\tfmt.Println("Usuario:", userID)\t}}


2. Autenticación mediante OAuth2



OAuth2 es un protocolo de acceso delegado que permite a los usuarios iniciar sesión a través de servicios de terceros (Google, GitHub, VK, etc.). En Go, la biblioteca popular es golang.org/x/oauth2.



Instalación:

go get golang.org/x/oauth2


Ejemplo de OAuth2 con Google:

package main

import (\t"context"\t"encoding/json"\t"fmt"\t"net/http"\t"golang.org/x/oauth2"\t"golang.org/x/oauth2/google")

var googleOauthConfig = &oauth2.Config{\tRedirectURL: "http://localhost:8080/callback",\tClientID: "your-client-id",\tClientSecret: "your-client-secret",\tScopes: []string{"https://www.googleapis.com/auth/userinfo.email"},\tEndpoint: google.Endpoint,}

func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {\turl := googleOauthConfig.AuthCodeURL("state-token")\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)}

func handleCallback(w http.ResponseWriter, r *http.Request) {\tcode := r.URL.Query().Get("code")\ttoken, err := googleOauthConfig.Exchange(context.Background(), code)\tif err != nil {\t\thttp.Error(w, "Error al intercambiar el token", http.StatusInternalServerError)\t\treturn\t}

\t// Obtención de datos del usuario\tclient := googleOauthConfig.Client(context.Background(), token)\tresp, _ := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")\tdefer resp.Body.Close()

\tvar userInfo map[string]interface{}\tjson.NewDecoder(resp.Body).Decode(&userInfo)\tfmt.Fprintf(w, "Email: %v", userInfo["email"])}

func main() {\thttp.HandleFunc("/auth/google", handleGoogleLogin)\thttp.HandleFunc("/callback", handleCallback)\thttp.ListenAndServe(":8080", nil)}


3. Autenticación por sesiones



Enfoque clásico que utiliza cookies y sesiones del lado del servidor. En Go, a menudo se usa...

Recommendations