echobasicauth

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: LGPL-3.0 Imports: 10 Imported by: 0

README

echo basic auth

Basic Auth middleware with constant time equality checks and optional IP whitelisting for Echo framework. CIDRs are supported for IP whitelisting as well

Usage

auth := &echobasicauth.Auth{Login: "test", Password: "test", IPs: []string{"127.0.0.1", "10.0.0.0/24"}}
e.Use(echobasicauth.NewMiddleware(auth))
// or you can use echobasicauth.NewValidator(auth) if you want to define the middleware yourself

IP rules match the transport peer, so X-Forwarded-For and X-Real-IP cannot spoof an allowlisted client. Proxy trust is opt-in:

e.IPExtractor = echo.ExtractIPFromXFFHeader()

Without it, proxied clients are checked against the proxy address. Auth.IPs changes apply on the next request. Invalid entries never open the whitelist: an all-invalid list denies everybody, and Validate reports the typos, so they can fail the boot instead of the check:

if err := auth.Validate(); err != nil {
    return err
}

Failed attempts are logged at WARN with the anonymized client address; Echo's default level is ERROR, so raise it to see them: e.Logger.SetLevel(log.WARN).

IP validation without credentials
auth := &echobasicauth.Auth{IPs: []string{"127.0.0.1", "10.0.0.0/24"}}
if auth.AllowedIP(echobasicauth.ClientIP(c)) {
    // IP is allowed
}

Use ClientIP instead of c.RealIP(): it ignores client headers unless e.IPExtractor is set, so the check cannot be bypassed with a crafted request.

Documentation

Index

Constants

View Source
const ContextLoginKey = "echo-basic-auth.login"

ContextLoginKey is the key used to store the login after successful auth in the context

Variables

This section is empty.

Functions

func ClientIP added in v1.4.2

func ClientIP(c echo.Context) string

ClientIP resolves the client address, trusting forwarded headers only when echo.IPExtractor is set

func NewMiddleware

func NewMiddleware(auths ...*Auth) echo.MiddlewareFunc

NewMiddleware returns a new BasicAuth middleware instance

func NewValidator

func NewValidator(auths ...*Auth) middleware.BasicAuthValidator

NewValidator returns a new BasicAuthValidator

Types

type Auth

type Auth struct {
	Login    string   `json:"login" yaml:"login"` // Basic auth login
	Password string   `json:"password" yaml:"password"`
	IPs      []string `json:"ips" yaml:"ips"` // Allowed IPs and CIDRs
	// contains filtered or unexported fields
}

Auth model

func (*Auth) AllowedIP added in v1.4.0

func (a *Auth) AllowedIP(ip string) bool

AllowedIP checks if the given IP is allowed by this Auth's IP rules

func (*Auth) Validate added in v1.4.2

func (a *Auth) Validate() error

Validate reports allowlist entries that are neither an IP nor a CIDR, so a typo fails the boot

Jump to

Keyboard shortcuts

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