Autorisation et authentification en Go (Golang)
La sécurité des applications web en Go commence par une implémentation correcte des mécanismes d'authentification (vérification de "qui vous êtes") et d'autorisation (vérification de "ce que vous avez le droit de faire"). Dans cet article, nous allons aborder trois approches principales : JWT (JSON Web Tokens), OAuth2 et l'authentification par session. Chacune a ses cas d'utilisation, ses avantages et ses inconvénients.
1. Authentification avec JWT (JSON Web Token)
JWT est un moyen compact et autonome de transmettre des informations entre les parties sous la forme d'un objet JSON. En Go, la bibliothèque la plus couramment utilisée pour travailler avec JWT est github.com/golang-jwt/jwt/v5.
Installation :
go get github.com/golang-jwt/jwt/v5Exemple de création et de vérification d'un JWT :
package main
import (\t"fmt"\t"time"\t"github.com/golang-jwt/jwt/v5")
var jwtSecret = []byte("my_secret_key")
// Création du jetonfunc 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)}
// Vérification du jetonfunc 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éthode de signature invalide")\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("jeton invalide")}
func main() {\ttoken, _ := createToken("user123")\tfmt.Println("Jeton :", token)
\tuserID, err := validateToken(token)\tif err != nil {\t\tfmt.Println("Erreur :", err)\t} else {\t\tfmt.Println("Utilisateur :", userID)\t}}2. Authentification via OAuth2
OAuth2 est un protocole d'accès délégué qui permet aux utilisateurs de se connecter via des services tiers (Google, GitHub, VK, etc.). En Go, la bibliothèque populaire est golang.org/x/oauth2.
Installation :
go get golang.org/x/oauth2Exemple OAuth2 avec 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, "Erreur d'échange de jeton", http.StatusInternalServerError)\t\treturn\t}
\t// Récupération des données utilisateur\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. Authentification par session
Approche classique utilisant des cookies et des sessions côté serveur. En Go, elle est souvent utilisée
Aussi dans la bibliothèque
proptest Rust : guide complet avec exemples concrets
Envoi de SMS en Go (Golang) : API de la bibliothèque golang-sms
Génération de rapports PDF en PHP : aperçu des bibliothèques et exemples
Travailler avec CSV en Kotlin : bibliothèques, analyse et écriture de données