Skip to content

Repository files navigation

go-security

A Go security framework: idiomatic Go, net/http-native middleware (no framework lock-in), better performance (no reflection-heavy proxies), and simple integration — one securityhttp builder wraps any handler.

Dependency guarantee: standard library + golang.org/x/crypto only. Verify with go list -deps ./.... Distributed (Redis) stores live in a separate module (github.com/thuongh2/go-security-redis) so this stays true.

Quickstart — the 5-line integration

handler, err := securityhttp.NewHandler(app,
    securityhttp.WithSessionStore(store, users),
    securityhttp.WithLogin("/login", manager),
    securityhttp.WithAuthorize(authz.Routes(
        authz.Match("/admin/**").HasRole("ADMIN"),
        authz.AnyRequest().Authenticated(),
    )),
)
if err != nil {
    log.Fatal(err) // fail loud: an incomplete authz set never ships
}
http.ListenAndServe(":8443", handler)

Secure defaults come for free: security headers on, CSRF on (session-backed), cookies Secure + HttpOnly + SameSite=Lax, authorization default-deny, and a fail-loud Build. The runnable example is examples/securityhttp/main.go. See docs/INTEGRATION.md for gradual adoption and docs/SECURITY.md for the threat model.

handler above wraps any http.Handler, so the same call integrates Gin, Echo, chi, gorilla/mux, or httprouter — no adapter, no framework-specific package. Fiber (fasthttp) bridges with adaptor.HTTPMiddleware. One runnable program per framework: examples/frameworks/.

Feature coverage

Feature go-security package Status
Security context core (on context.Context)
Authentication / authorities core
Provider manager authn.Manager
DAO authentication authn.PasswordProvider
User details service authn.UserService
Password encoders crypto/password
Filter chain web/middleware, securityhttp
HTTP security DSL securityhttp
Authorization rules authz
Form login web/auth
Session management web/session
Session context filter securityhttp.SessionAuthentication
CSRF web/csrf
CORS / headers web/cors, web/middleware
Remember-me web/rememberme
Anonymous auth web/middleware
OAuth2 client / login oauth2, authn
JWT / resource server jwt, web/resource
Audit / events core/event
Rate limiting ratelimit
Account lockout lockout
Metrics / observability observe ✅ (bridge yourself)
Distributed stores go-security-redis (separate module) 📄 contracts here

Package index

Package What it provides
core Authentication, Authority, security context, sentinel errors
core/event Authentication event publisher (audit / lockout hook)
crypto/password bcrypt, argon2id, algorithm-tagged delegating encoder
authn Manager, PasswordProvider, UserService, OAuth2 / bearer providers
authz First-match-wins, default-deny route authorization DSL + role hierarchy
web/middleware Chain, ant-path matchers, security headers, basic auth, anonymous
web/session Pluggable session store + fixation protection
web/csrf Synchronizer + double-submit CSRF
web/cors CORS (refuses cred+wildcard at construction)
web/auth JSON form-login + logout handlers
web/rememberme Signed remember-me cookie
web/resource Bearer-token resource-server middleware
jwt HS/RS/ES/EdDSA sign & verify, JWKS fetch/cache
oauth2 Authorization-code client, PKCE, OIDC
ratelimit Token-bucket limiter, trusted-proxy client IP, login throttle
lockout Failure-counting account lockout (check-before-KDF)
observe Low-cardinality metrics interface + slog hooks (no metrics dep)
securityhttp The HttpSecurity-style builder; secure defaults

Performance

go-security is net/http-native with no reflection-heavy proxy chain. A benchmark suite (in *_bench_test.go files) measures the overhead vs raw net/http:

Benchmark What it measures Target
BenchmarkChainOverhead a middleware.Chain of N middlewares vs raw handler < 1 µs/req
BenchmarkBasicAuth BasicAuth header parse + provider (fixed-cost encoder)
BenchmarkSessionLookup MemoryStore.Get hot path
BenchmarkJWTVerify/{HS256,RS256,ES256,EdDSA} per-algorithm verify
BenchmarkRouteMatch authz matcher dispatch over a realistic rule table
BenchmarkTokenBucketAllow TokenBucketLimiter.Allow (single + multi key)
BenchmarkSecurityHTTPChain the assembled securityhttp chain vs raw

The "< 1 µs/req chain overhead" goal is a documented target with a committed benchstat baseline, not a CI hard-fail (perf gates are environment-dependent and flaky as merge blockers). Run:

go test -bench=. -benchmem ./...

Conventions

  • Go 1.24, stdlib-first; allowed deps: golang.org/x/crypto, golang.org/x/oauth2.
  • Everything is an interface with a sane default impl; zero global state — context-scoped.
  • Errors: sentinel errors in core wrapped with %w; match with errors.Is.
  • See ROADMAP.md for the phase history.

About

A Go security framework: idiomatic Go, net/http-native middleware, better performance, and simple integration

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages