auth

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 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

See the Quick Start example for a complete, runnable example of how to use the Auth module.

Configuration

The auth module can be configured using the Config struct. See the Configuration example for a complete, runnable example of how to configure the Auth module.

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

See the Auth Instance example for a complete, runnable example of how to create an Auth instance.

Middleware

See the Middleware example for a complete, runnable example of how to use the Auth middleware.

Token Handling

See the Token Handling example for a complete, runnable example of how to generate and validate tokens.

Authorization

See the Authorization example for a complete, runnable example of how to perform authorization checks.

User Information

See the User Information example for a complete, runnable example of how to get user information from the context.

Context Utilities

The auth module provides utilities for working with context. See the Context Utilities example for a complete, runnable example of how to use these utilities.

Error Handling

The auth module provides comprehensive error handling with context-aware errors. See the Error Handling example for a complete, runnable example of how to handle errors.

Best Practices

  1. Secure Secret Keys: Always store JWT secret keys securely, preferably in environment variables or a secure key management system.

  2. Token Expiration: Set appropriate expiration times for tokens based on your security requirements.

  3. HTTPS: Always use HTTPS in production to protect tokens in transit.

  4. Validate All Tokens: Always validate tokens before trusting their contents.

  5. Role-Based Access Control: Use role-based access control to limit access to sensitive operations.

  6. Error Handling: Implement proper error handling for authentication and authorization failures.

  7. Logging: Log authentication and authorization events for audit purposes, but be careful not to log sensitive information.

Troubleshooting

Common Issues
Token Validation Failures

Issue: JWT token validation fails with "invalid signature" error.

Solution: Ensure that the same secret key is used for both token generation and validation. Check that the token hasn't been tampered with.

OIDC Provider Connection Issues

Issue: Unable to connect to the OIDC provider.

Solution: Check network connectivity, firewall settings, and that the OIDC provider is running and accessible.

Authorization Failures

Issue: User has the correct token but is not authorized to perform an operation.

Solution: Check that the user has the required roles or permissions for the operation. Verify that the role-based access control configuration is correct.

  • Middleware - The middleware component includes HTTP middleware for authentication and authorization.
  • Context - The context component provides utilities for working with context, which is used extensively in the auth module.
  • Logging - The logging component provides structured logging, which is used by the auth module for logging authentication and authorization events.
  • Telemetry - The telemetry component provides tracing, which is used by the auth module for tracing authentication and authorization operations.

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

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.

Package auth provides authentication and authorization functionality. This file contains compatibility functions for the old auth/errors package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidToken is returned when a token is invalid
	ErrInvalidToken = errors.NewAuthenticationError("invalid token", "", nil)

	// ErrExpiredToken is returned when a token has expired
	ErrExpiredToken = errors.NewAuthenticationError("token expired", "", nil)

	// ErrMissingToken is returned when a token is missing
	ErrMissingToken = errors.NewAuthenticationError("token missing", "", nil)

	// ErrInvalidSignature is returned when a token has an invalid signature
	ErrInvalidSignature = errors.NewAuthenticationError("invalid token signature", "", nil)

	// ErrInvalidClaims is returned when a token has invalid claims
	ErrInvalidClaims = errors.NewAuthenticationError("invalid token claims", "", nil)

	// ErrUnauthorized is returned when a user is not authorized to perform an operation
	ErrUnauthorized = errors.ErrUnauthorized

	// ErrForbidden is returned when a user is forbidden from performing an operation
	ErrForbidden = errors.ErrForbidden

	// ErrInvalidConfig is returned when the configuration is invalid
	ErrInvalidConfig = errors.NewConfigurationError("invalid configuration", "", "", nil)

	// ErrInternal is returned when an internal error occurs
	ErrInternal = errors.ErrInternal

	// ErrNotImplemented is returned when a feature is not implemented
	ErrNotImplemented = errors.New(errors.InternalErrorCode, "not implemented")
)

Error constants for backward compatibility

Functions

func GetContext added in v1.4.0

func GetContext(err error, key string) (interface{}, bool)

GetContext gets a context value from an error for backward compatibility

func GetMessage added in v1.4.0

func GetMessage(err error) (string, bool)

GetMessage gets the message from an error for backward compatibility

func GetOp added in v1.4.0

func GetOp(err error) (string, bool)

GetOp gets the operation from an error for backward compatibility

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 WithContext added in v1.4.0

func WithContext(err error, key string, value interface{}) error

WithContext adds context to an error for backward compatibility

func WithMessage added in v1.4.0

func WithMessage(err error, message string) error

WithMessage adds a message to an error for backward compatibility

func WithOp added in v1.4.0

func WithOp(err error, op string) error

WithOp adds an operation to an error for backward compatibility

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.

func Wrap added in v1.4.0

func Wrap(err error, message string) error

Wrap wraps an error with a message for backward compatibility

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