auth

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 11 Imported by: 0

README

auth — JWT HS256 authentication and OAuth2

auth provides JWT token generation/validation, HTTP middleware, cookie management, and Google OAuth2 for the HOROS ecosystem.

Quick start

// Generate a token.
token, _ := auth.GenerateToken(secret, &auth.HorosClaims{
    RegisteredClaims: jwt.RegisteredClaims{Subject: "user123"},
    Email: "user@example.com",
    Role:  "admin",
}, 24*time.Hour)

// Validate.
claims, _ := auth.ValidateToken(secret, token)

// HTTP middleware — extracts JWT from cookie or Authorization header.
mux.Handle("/api/", auth.Middleware(secret)(apiHandler))

Security

  • HS256 only — signing algorithm is pinned; rejects tokens using other algorithms.
  • 32-byte minimum secret — enforced via horosafe.ValidateSecret.
  • HttpOnly + SameSite=Strict cookies — prevents XSS and CSRF.

OAuth2 Google

oauthCfg := auth.NewGoogleProvider(auth.OAuthConfig{
    ClientID: "...", ClientSecret: "...", RedirectURL: "...",
})
user, _ := auth.FetchGoogleUser(ctx, oauthCfg, code)
// user.Email, user.Name, user.AvatarURL

Exported API

Symbol Description
HorosClaims JWT claims with UserID, Email, Role, Handle, AvatarURL, AuthProvider
GenerateToken(secret, claims, expiry) Create signed JWT
ValidateToken(secret, tokenStr) Parse and verify JWT
Middleware(secret) HTTP middleware injecting claims into context
RequireAuth Middleware redirecting unauthenticated requests to /login
GetClaims(ctx) Retrieve HorosClaims from context
SetTokenCookie / ClearTokenCookie Cookie helpers
NewGoogleProvider(cfg) Create Google OAuth2 config
FetchGoogleUser(ctx, cfg, code) Exchange OAuth code for user profile

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearTokenCookie

func ClearTokenCookie(w http.ResponseWriter, domain string)

ClearTokenCookie removes the JWT cookie, matching the same Domain attribute so that cross-subdomain cookies are properly cleared.

func GenerateToken

func GenerateToken(secret []byte, claims *HorosClaims, expiry time.Duration) (string, error)

GenerateToken creates a signed JWT string from the given claims. The expiry duration is added to the current time to set the ExpiresAt field. Returns an error if the secret is shorter than horosafe.MinSecretLen bytes.

func Middleware

func Middleware(secret []byte) func(http.Handler) http.Handler

Middleware returns an http.Handler middleware that extracts a JWT from the "token" cookie (preferred) or the Authorization Bearer header. If valid, the parsed HorosClaims are injected into the request context along with kit.UserIDKey and kit.HandleKey for interoperability with the kit layer. Invalid or missing tokens are silently ignored — use RequireAuth to enforce.

func NewGoogleProvider

func NewGoogleProvider(cfg OAuthConfig) *oauth2.Config

NewGoogleProvider returns an oauth2.Config configured for Google login with email and profile scopes.

func RequireAuth

func RequireAuth(next http.Handler) http.Handler

RequireAuth is an http.Handler middleware that redirects unauthenticated requests to /login. It checks for the presence of HorosClaims in context.

func SetTokenCookie

func SetTokenCookie(w http.ResponseWriter, token, domain string, secure bool)

SetTokenCookie writes the JWT token as an HttpOnly cookie. When domain is non-empty, the cookie is set with that Domain attribute, enabling cross-subdomain SSO (e.g. Domain=".docbusinessia.fr").

func ValidateTokenMapClaims

func ValidateTokenMapClaims(secret []byte, tokenStr string) (jwt.MapClaims, error)

ValidateTokenMapClaims parses a JWT and returns raw MapClaims for backward compatibility with services that still expect unstructured claims. Strictly pins the signing method to HS256.

Types

type HorosClaims

type HorosClaims struct {
	jwt.RegisteredClaims
	UserID       string `json:"user_id"`
	Username     string `json:"username"`
	Handle       string `json:"handle,omitempty"`
	Role         string `json:"role"`
	Email        string `json:"email,omitempty"`
	DisplayName  string `json:"display_name,omitempty"`
	AvatarURL    string `json:"avatar_url,omitempty"`
	AuthProvider string `json:"auth_provider,omitempty"` // "local", "google", "github"
}

HorosClaims defines the unified JWT claims structure for all HOROS services. It embeds jwt.RegisteredClaims for standard fields (exp, iat, etc.) and adds HOROS-specific fields for user identity and auth provider tracking.

func GetClaims

func GetClaims(ctx context.Context) *HorosClaims

GetClaims retrieves the HorosClaims from the context, or nil if absent.

func ValidateToken

func ValidateToken(secret []byte, tokenStr string) (*HorosClaims, error)

ValidateToken parses and validates a JWT string, returning the structured HorosClaims. Strictly pins the signing method to HS256 to prevent algorithm confusion attacks.

type OAuthConfig

type OAuthConfig struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
}

OAuthConfig holds the configuration needed to set up an OAuth2 provider.

type OAuthUser

type OAuthUser struct {
	ProviderUserID string
	Email          string
	Name           string
	AvatarURL      string
}

OAuthUser represents the normalized user profile returned by an OAuth2 provider.

func FetchGoogleUser

func FetchGoogleUser(ctx context.Context, oauthCfg *oauth2.Config, code string) (*OAuthUser, *oauth2.Token, error)

FetchGoogleUser exchanges an OAuth2 token for the user's Google profile.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL