auth

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 13 Imported by: 0

README

Auth Module

The Auth Module provides comprehensive authentication and authorization functionality for Go applications. It includes JWT token handling, OIDC integration, HTTP middleware, and role-based access control.

Features

  • JWT Token Handling: Generate and validate JWT tokens
  • OIDC Integration: Validate tokens from OpenID Connect providers
  • HTTP Middleware: Authenticate HTTP requests
  • Role-Based Access Control: Control access to resources based on user roles
  • Comprehensive Error Handling: Context-aware error handling with detailed error information
  • Tracing Integration: OpenTelemetry tracing for all operations
  • Logging Integration: Structured logging with zap

Installation

go get github.com/abitofhelp/servicelib/auth

Quick Start

package main

import (
    "context"
    "net/http"
    "time"

    "github.com/abitofhelp/servicelib/auth"
    "go.uber.org/zap"
)

func main() {
    // Create a logger
    logger, _ := zap.NewProduction()
    defer logger.Sync()

    // Create a context
    ctx := context.Background()

    // Create a configuration
    config := auth.DefaultConfig()
    config.JWT.SecretKey = "your-secret-key"

    // Create an auth instance
    authInstance, err := auth.New(ctx, config, logger)
    if err != nil {
        logger.Fatal("Failed to create auth instance", zap.Error(err))
    }

    // Create an HTTP handler
    http.Handle("/", authInstance.Middleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Check if the user is authorized to perform an operation
        authorized, err := authInstance.IsAuthorized(r.Context(), "read:resource")
        if err != nil {
            http.Error(w, "Authorization error", http.StatusInternalServerError)
            return
        }

        if !authorized {
            http.Error(w, "Forbidden", http.StatusForbidden)
            return
        }

        // Get the user ID
        userID, err := authInstance.GetUserID(r.Context())
        if err != nil {
            http.Error(w, "User ID not found", http.StatusInternalServerError)
            return
        }

        w.Write([]byte("Hello, " + userID))
    })))

    // Start the server
    http.ListenAndServe(":8080", nil)
}

Configuration

The auth module can be configured using the Config struct:

config := auth.Config{}

// JWT configuration
config.JWT.SecretKey = "your-secret-key"
config.JWT.TokenDuration = 24 * time.Hour
config.JWT.Issuer = "your-issuer"

// JWT Remote validation configuration
config.JWT.Remote.Enabled = true
config.JWT.Remote.ValidationURL = "https://your-auth-server.com/validate"
config.JWT.Remote.ClientID = "your-client-id"
config.JWT.Remote.ClientSecret = "your-client-secret"
config.JWT.Remote.Timeout = 5 * time.Second

// OIDC configuration
config.OIDC.IssuerURL = "https://your-oidc-provider.com"
config.OIDC.ClientID = "your-client-id"
config.OIDC.ClientSecret = "your-client-secret"
config.OIDC.RedirectURL = "https://your-app.com/callback"
config.OIDC.Scopes = []string{"openid", "profile", "email"}
config.OIDC.Timeout = 10 * time.Second

// Middleware configuration
config.Middleware.SkipPaths = []string{"/public", "/health"}
config.Middleware.RequireAuth = true

// Service configuration
config.Service.AdminRoleName = "admin"
config.Service.ReadOnlyRoleName = "reader"
config.Service.ReadOperationPrefixes = []string{"read:", "list:", "get:"}

API Documentation

Auth

The Auth struct is the main entry point for the auth module. It provides methods for authentication and authorization.

Creating an Auth Instance
authInstance, err := auth.New(ctx, config, logger)
Middleware
// Get the middleware function
middleware := authInstance.Middleware()

// Use the middleware with an HTTP handler
http.Handle("/", middleware(yourHandler))
Token Handling
// Generate a token
token, err := authInstance.GenerateToken(ctx, "user123", []string{"admin"})

// Validate a token
claims, err := authInstance.ValidateToken(ctx, token)
Authorization
// Check if the user is authorized to perform an operation
authorized, err := authInstance.IsAuthorized(ctx, "read:resource")

// Check if the user has admin role
isAdmin, err := authInstance.IsAdmin(ctx)

// Check if the user has a specific role
hasRole, err := authInstance.HasRole(ctx, "editor")
User Information
// Get the user ID from the context
userID, err := authInstance.GetUserID(ctx)

// Get the user roles from the context
roles, err := authInstance.GetUserRoles(ctx)
Context Utilities

The auth module provides utilities for working with context:

// Add user ID to context
ctx = auth.WithUserID(ctx, "user123")

// Add user roles to context
ctx = auth.WithUserRoles(ctx, []string{"admin", "editor"})

// Get user ID from context
userID, ok := auth.GetUserIDFromContext(ctx)

// Get user roles from context
roles, ok := auth.GetUserRolesFromContext(ctx)

// Check if the user is authenticated
isAuthenticated := auth.IsAuthenticated(ctx)

Error Handling

The auth module provides comprehensive error handling with context-aware errors:

import "github.com/abitofhelp/servicelib/auth/errors"

// Check for specific error types
if errors.Is(err, errors.ErrInvalidToken) {
    // Handle invalid token error
}

// Get context information from an error
if value, ok := errors.GetContext(err, "key"); ok {
    // Use the context value
}

// Get the operation that caused the error
if op, ok := errors.GetOp(err); ok {
    // Use the operation
}

// Get the error message
if message, ok := errors.GetMessage(err); ok {
    // Use the message
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package auth provides authentication and authorization functionality. It includes JWT token handling, OIDC integration, HTTP middleware, and role-based access control.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) (string, bool)

GetUserIDFromContext retrieves the user ID from the context.

func GetUserRolesFromContext

func GetUserRolesFromContext(ctx context.Context) ([]string, bool)

GetUserRolesFromContext retrieves the user roles from the context.

func IsAuthenticated

func IsAuthenticated(ctx context.Context) bool

IsAuthenticated checks if the user is authenticated.

func ValidateConfig

func ValidateConfig(config Config) *validation.ValidationResult

ValidateConfig validates the configuration for the auth module.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID returns a new context with the user ID.

func WithUserRoles

func WithUserRoles(ctx context.Context, roles []string) context.Context

WithUserRoles returns a new context with the user roles.

Types

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth provides authentication and authorization functionality.

func New

func New(ctx context.Context, config Config, logger *zap.Logger) (*Auth, error)

New creates a new Auth instance with the provided configuration and logger.

func (*Auth) GenerateToken

func (a *Auth) GenerateToken(ctx context.Context, userID string, roles []string, scopes []string, resources []string) (string, error)

GenerateToken generates a new JWT token for a user with the specified roles, scopes, and resources.

func (*Auth) GetUserID

func (a *Auth) GetUserID(ctx context.Context) (string, error)

GetUserID retrieves the user ID from the context.

func (*Auth) GetUserRoles

func (a *Auth) GetUserRoles(ctx context.Context) ([]string, error)

GetUserRoles retrieves the user roles from the context.

func (*Auth) HasRole

func (a *Auth) HasRole(ctx context.Context, role string) (bool, error)

HasRole checks if the user has a specific role.

func (*Auth) IsAdmin

func (a *Auth) IsAdmin(ctx context.Context) (bool, error)

IsAdmin checks if the user has admin role.

func (*Auth) IsAuthorized

func (a *Auth) IsAuthorized(ctx context.Context, operation string) (bool, error)

IsAuthorized checks if the user is authorized to perform the operation.

func (*Auth) Middleware

func (a *Auth) Middleware() func(http.Handler) http.Handler

Middleware returns the HTTP middleware for authentication.

func (*Auth) ValidateToken

func (a *Auth) ValidateToken(ctx context.Context, tokenString string) (*jwt.Claims, error)

ValidateToken validates a JWT token and returns the claims if valid.

type Config

type Config struct {
	// JWT configuration
	JWT struct {
		// SecretKey is the key used to sign and verify JWT tokens
		SecretKey string

		// TokenDuration is the validity period for generated tokens
		TokenDuration time.Duration

		// Issuer identifies the entity that issued the token
		Issuer string

		// Remote validation configuration
		Remote struct {
			// Enabled determines if remote validation should be used
			Enabled bool

			// ValidationURL is the URL of the remote validation endpoint
			ValidationURL string

			// ClientID is the client ID for the remote validation service
			ClientID string

			// ClientSecret is the client secret for the remote validation service
			ClientSecret string

			// Timeout is the timeout for remote validation operations
			Timeout time.Duration
		}
	}

	// OIDC configuration
	OIDC struct {
		// IssuerURL is the URL of the OIDC provider
		IssuerURL string

		// ClientID is the client ID for the OIDC provider
		ClientID string

		// ClientSecret is the client secret for the OIDC provider
		ClientSecret string

		// RedirectURL is the redirect URL for the OIDC provider
		RedirectURL string

		// Scopes are the OAuth2 scopes to request
		Scopes []string

		// Timeout is the timeout for OIDC operations
		Timeout time.Duration
	}

	// Middleware configuration
	Middleware struct {
		// SkipPaths are paths that should skip authentication
		SkipPaths []string

		// RequireAuth determines if authentication is required for all requests
		RequireAuth bool
	}

	// Service configuration
	Service struct {
		// AdminRoleName is the name of the admin role
		AdminRoleName string

		// ReadOnlyRoleName is the name of the read-only role
		ReadOnlyRoleName string

		// ReadOperationPrefixes are prefixes for read-only operations
		ReadOperationPrefixes []string
	}
}

Config holds the configuration for the auth module.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration for the auth module.

Directories

Path Synopsis
Package config provides adapters for auth configuration.
Package config provides adapters for auth configuration.
Package errors provides comprehensive error handling for the auth module.
Package errors provides comprehensive error handling for the auth module.
Package jwt provides JWT token handling for the auth module.
Package jwt provides JWT token handling for the auth module.
Package middleware provides HTTP middleware for authentication.
Package middleware provides HTTP middleware for authentication.
Package oidc provides OpenID Connect integration for the auth module.
Package oidc provides OpenID Connect integration for the auth module.
Package service provides authorization services for the auth module.
Package service provides authorization services for the auth module.

Jump to

Keyboard shortcuts

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