authula

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README ΒΆ

Authula Logo


Introduction

✨ Overview

Authula is an open-source authentication solution that scales with you. Embed it as a library in your Go app, or run it as a standalone auth server with any tech stack. It simplifies adding robust authentication to backend services, empowering developers to build secure applications faster.

All functionality is delivered through a powerful plugin system, allowing you to compose exactly the authentication stack you need β€” no more, no less, all built with clean architecture. Authula is flexible enough to integrate with any technology stack. It streamlines the implementation of essential security features through a clean, modular architecture, allowing developers to concentrate on building their applications without the overhead of managing authentication complexities.


🎯 Who is it for?

Authula is ideal for:

  • Startups that want full control over their authentication stack
  • Teams building microservices or multi-backend systems
  • Companies with self-hosting or compliance requirements
  • Go developers who want first-class embedded auth
  • Anyone who wants modern auth without SaaS lock-in

🧩 Plugins & Capabilities

Authula is architected around a powerful plugin and capability system.

Plugins are modular packages that encapsulate related authentication features.
Capabilities represent individual, fine-grained functionalities exposed by these plugins.

Each plugin can offer multiple capabilities, and every route in your application explicitly declares which capabilities it leverages. This approach ensures that authentication logic is:

  • Explicit – No hidden behaviors; every capability is clearly declared.
  • Composable – Mix and match only the features you need.
  • Auditable – Easily track which routes use which authentication features.
  • Understandable – The authentication flow is transparent and easy to reason about.

This design empowers you to build secure, maintainable, and highly customizable authentication flows tailored to your application's needs.


Features

Authula comes with a variety of plugins that provide essential authentication features out of the box:

  • πŸ“§ Email & Password: Authentication, Email Verification & Password Reset
  • 🌐 OAuth providers
  • πŸ” TOTP: Authenticator app support, backup codes, trusted devices for two-factor authentication
  • πŸ’Ύ Multiple database backends
  • πŸ—„οΈ Secondary storage (Redis, memory, DB)
  • ⚑ Rate limiting
  • πŸ›‘οΈ CSRF protection
  • πŸͺ Hooks system
  • πŸ“¨ Event bus
  • 🧩 Custom routes and logic

Hooks System

Authula includes a powerful, lifecycle-based hooks system that lets you intercept and customize request handling at every stage of the HTTP pipeline.

Hooks allow you to implement:

  • custom authentication logic
  • request validation
  • logging & tracing
  • metrics
  • access control
  • A/B testing
  • feature flags
  • audit trails
  • custom headers
  • dynamic routing

All without modifying core code.

Build your own plugins for:

  • business logic
  • custom routes
  • custom auth flows
  • external integrations
  • internal tooling

Deployment Modes

Embedded Mode (Go Library)

Embed Authula directly into your Go application:

import (
  authula "github.com/Authula/authula"
  authulaconfig "github.com/Authula/authula/config"
  authulamodels "github.com/Authula/authula/models"
  authulaenv "github.com/Authula/authula/env"
)

config := authulaconfig.NewConfig(
  authulaconfig.WithAppName("AuthulaPlayground"),
  authulaconfig.WithBasePath("/api/auth"),
  authulaconfig.WithDatabase(authulamodels.DatabaseConfig{
    Provider: "postgres",
    URL:      os.Getenv(authulaenv.EnvDatabaseURL),
  }),
  // other config options...
)

auth := authula.New(authula.AuthConfig{
  Config:  config,
  Plugins: []authulamodels.Plugin{
    emailpasswordplugin.New(...),
    // other plugins...
  },
})

http.ListenAndServe(":8080", auth.Handler())

You get:

  • zero network overhead
  • full type safety
  • native integration
  • maximum performance

Standalone Mode

Run Authula as a standalone authentication server via Docker:

docker run -itd -p 8080:8080 \
  -v $(pwd)/config.toml:/home/appuser/config.toml \
  -e AUTHULA_BASE_URL=http://localhost:8080 \
  -e AUTHULA_SECRET=my-app-secret \
  -e AUTHULA_DATABASE_URL=<your_connection_string> \
  # other env vars depending on plugins used...
  ghcr.io/authula/authula:latest

Use it from any language or framework over HTTP.


🧠 Design Principles

  • Plugin-first architecture
  • Clean architecture
  • Minimal dependencies
  • Standard library first
  • Secure by default
  • Framework agnostic
  • Self-hosted
  • Extensible

Docs

For more info and a full guide on how to use this library, check out the Docs.


SDKs

We provide the following SDKs to facilitate easy integration with Authula:


Contributing

Your contributions are welcome! Here's how you can get involved:

Star History Chart


Support & Community

Join our growing community for support, discussions, and updates:


πŸ’Ž Support Development

If you'd like to support the ongoing development of this project, consider subscribing on Polar, it means a lot to me!

Subscribe on Polar


πŸ’– Our Sponsors

🏒 Corporate Sponsors

πŸ₯‡ Gold Sponsors

πŸ₯ˆ Silver Sponsors

πŸ₯‰ Bronze Sponsors


Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func InitCoreServices ΒΆ

func InitCoreServices(config *models.Config, db bun.IDB, serviceRegistry models.ServiceRegistry) *coreservices.CoreServices

func InitCoreSystems ΒΆ

func InitCoreSystems(logger models.Logger, config *models.Config, coreServices *coreservices.CoreServices) []models.CoreSystem

func InitDatabase ΒΆ

func InitDatabase(config *models.Config, logger models.Logger, logLevel string) (bun.IDB, error)

InitDatabase creates a Bun DB connection based on provider

func InitEventBus ΒΆ

func InitEventBus(config *models.Config) (models.EventBus, error)

InitEventBus creates an event bus based on the configuration

func InitLogger ΒΆ

func InitLogger(config *models.Config) models.Logger

InitLogger initializes the logger based on configuration

Types ΒΆ

type Auth ΒΆ

type Auth struct {
	ServiceRegistry models.ServiceRegistry
	PluginRegistry  models.PluginRegistry

	Api internal.CoreAPI
	// contains filtered or unexported fields
}

Auth is a composition root and entry point for the authentication framework.

func New ΒΆ

func New(authConfig *AuthConfig) *Auth

New creates a new Auth instance using the provided config and plugins. Handles plugin registration, migrations, and initialization in unified way. Works identically whether plugins are manually instantiated or built from config.

func (*Auth) ClosePlugins ΒΆ

func (auth *Auth) ClosePlugins() error

ClosePlugins calls Close for all registered plugins

func (*Auth) CloseSystems ΒΆ

func (auth *Auth) CloseSystems() error

func (*Auth) CoreServices ΒΆ

func (auth *Auth) CoreServices() *coreservices.CoreServices

func (*Auth) DB ΒΆ

func (auth *Auth) DB() bun.IDB

func (*Auth) DropCoreMigrations ΒΆ

func (auth *Auth) DropCoreMigrations(ctx context.Context) error

func (*Auth) GetUserIDFromContext ΒΆ

func (auth *Auth) GetUserIDFromContext(ctx context.Context) (string, bool)

GetUserIDFromContext retrieves the user ID from a context. Returns the user ID and a boolean indicating whether it was found. This is a convenience wrapper around models.GetUserIDFromContext to avoid requiring application code to import the models package.

func (*Auth) GetUserIDFromRequest ΒΆ

func (auth *Auth) GetUserIDFromRequest(req *http.Request) (string, bool)

GetUserIDFromRequest retrieves the user ID from an HTTP request's context. Returns the user ID and a boolean indicating whether it was found. This is a convenience wrapper around models.GetUserIDFromRequest to avoid requiring application code to import the models package.

func (*Auth) Handler ΒΆ

func (auth *Auth) Handler() http.Handler

Handler returns the HTTP handler that serves all authentication routes and hooks. It registers routes and hooks from all plugins with the router. This is the entry point for HTTP traffic.

func (*Auth) MigrationManager ΒΆ

func (auth *Auth) MigrationManager() *migrationmanager.Manager

func (*Auth) Migrator ΒΆ

func (auth *Auth) Migrator() *migrations.Migrator

func (*Auth) RegisterCustomRoute ΒΆ

func (auth *Auth) RegisterCustomRoute(route models.Route)

RegisterCustomRoute registers a single custom route without the basePath prefix This is useful for application routes that should not be under the auth basePath

func (*Auth) RegisterCustomRouteGroup ΒΆ

func (auth *Auth) RegisterCustomRouteGroup(group models.RouteGroup)

RegisterCustomRouteGroup registers a route group that can have a prefix path and metadata that applies to all routes This is useful if many routes should share paths and or metadata

func (*Auth) RegisterCustomRoutes ΒΆ

func (auth *Auth) RegisterCustomRoutes(routes []models.Route)

RegisterCustomRoutes registers multiple custom routes without the basePath prefix This is useful for application routes that should not be under the auth basePath

func (*Auth) RegisterHook ΒΆ

func (auth *Auth) RegisterHook(hook models.Hook)

RegisterHook registers a single hook to the router. Hooks allow developers to intercept and modify requests/responses at various stages of the request lifecycle (OnRequest, Before, After, OnResponse).

func (*Auth) RegisterHooks ΒΆ

func (auth *Auth) RegisterHooks(hooks []models.Hook)

RegisterHooks registers multiple hooks to the router. Hooks allow developers to intercept and modify requests/responses at various stages of the request lifecycle (OnRequest, Before, After, OnResponse).

func (*Auth) RegisterMiddleware ΒΆ

func (auth *Auth) RegisterMiddleware(middleware ...func(http.Handler) http.Handler)

RegisterMiddleware registers middleware to the chi router. Middleware should be registered before calling Handler().

func (*Auth) RegisterRoute ΒΆ

func (auth *Auth) RegisterRoute(route models.Route)

RegisterRoute registers a single route with the basePath prefix

func (*Auth) RegisterRoutes ΒΆ

func (auth *Auth) RegisterRoutes(routes []models.Route)

RegisterRoutes registers multiple routes with the basePath prefix

func (*Auth) Router ΒΆ

func (auth *Auth) Router() *Router

func (*Auth) RunCoreMigrations ΒΆ

func (auth *Auth) RunCoreMigrations(ctx context.Context) error

type AuthConfig ΒΆ

type AuthConfig struct {
	Config  *models.Config
	Plugins []models.Plugin
	DB      bun.IDB
}

type HookErrorMode ΒΆ

type HookErrorMode string

HookErrorMode defines how the router handles errors from hook handlers

const (
	// HookErrorModeContinue logs errors but continues to next hook (default)
	HookErrorModeContinue HookErrorMode = "error-log-continue"
	// HookErrorModeFailFast logs error and sets ctx.Handled=true to skip remaining hooks in current stage
	HookErrorModeFailFast HookErrorMode = "error-log-fail-fast"
	// HookErrorModeSilent silently ignores errors without logging
	HookErrorModeSilent HookErrorMode = "error-silent"
)

type HookType ΒΆ

type HookType string

HookErrorMode defines how the router handles errors from hook handlers

const (
	// HookTypeSync indicates a synchronous hook that runs in the main request flow
	HookTypeSync HookType = "sync"
	// HookTypeAsync indicates an asynchronous hook that runs in a background goroutine
	HookTypeAsync HookType = "async"
)

type Router ΒΆ

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

Router wraps chi.Router and manages hooks for the request lifecycle

func NewRouter ΒΆ

func NewRouter(config *models.Config, logger models.Logger, opts *RouterOptions) *Router

NewRouter creates a new Router with Chi as the underlying router opts can be nil to use default options

func (*Router) Get ΒΆ

func (r *Router) Get() chi.Router

Get returns the underlying chi.Router for direct access

func (*Router) Handler ΒΆ

func (r *Router) Handler() http.Handler

Handler returns the configured HTTP handler - the Router with hook middleware

func (*Router) RegisterCustomRoute ΒΆ

func (r *Router) RegisterCustomRoute(route models.Route)

RegisterCustomRoute registers a custom route without the basePath prefix This is useful for application routes that should not be under the auth basePath

func (*Router) RegisterCustomRouteGroup ΒΆ

func (r *Router) RegisterCustomRouteGroup(group models.RouteGroup)

RegisterCustomRouteGroup simplifies the management of multiple routes, by allowing to assign a base path and metadata to all child routes.

func (*Router) RegisterCustomRoutes ΒΆ

func (r *Router) RegisterCustomRoutes(routes []models.Route)

RegisterCustomRoutes registers multiple custom routes without the basePath prefix This is useful for application routes that should not be under the auth basePath

func (*Router) RegisterHook ΒΆ

func (r *Router) RegisterHook(hook models.Hook)

RegisterHook registers a single hook

func (*Router) RegisterHooks ΒΆ

func (r *Router) RegisterHooks(hooks []models.Hook)

RegisterHooks registers multiple hooks

func (*Router) RegisterMiddleware ΒΆ

func (r *Router) RegisterMiddleware(middleware ...func(http.Handler) http.Handler)

RegisterMiddleware registers global middleware with Chi

func (*Router) RegisterRoute ΒΆ

func (r *Router) RegisterRoute(route models.Route)

RegisterRoute registers a single route with Chi

func (*Router) RegisterRoutes ΒΆ

func (r *Router) RegisterRoutes(routes []models.Route)

RegisterRoutes registers multiple routes with an optional base path

func (*Router) ServeHTTP ΒΆ

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler for testing and direct use

func (*Router) SetRouteMetadataFromConfig ΒΆ

func (r *Router) SetRouteMetadataFromConfig(routeMetadata map[string]map[string]any)

SetRouteMetadataFromConfig sets route metadata mappings from RouteMappings. This populates the internal metadata map used to assign ctx.Route.Metadata["plugins"] during request handling. Supports both static and dynamic (parameterized) routes. Format: routeMetadata["METHOD:path"] = {"plugins": ["plugin1", "plugin2"], ...} Examples:

  • Static route: "GET:/me" -> plugins for GET /me
  • Dynamic route: "POST:/oauth2/callback/{provider}" -> plugins for POST /oauth2/callback/{provider} (matches any provider value)
  • Multi-param: "GET:/users/{id}/posts/{postId}" -> plugins for any GET request with that pattern

Dynamic routes use {paramName} syntax and match any actual parameter value at that position. At request time, the router first tries exact path matching, then falls back to pattern matching.

type RouterOptions ΒΆ

type RouterOptions struct {
	// AsyncHookTimeout is the timeout for async hook execution (default: 30 seconds)
	// If a hook takes longer than this, it will be cancelled
	AsyncHookTimeout time.Duration
	// HookErrorMode defines how errors from hooks are handled (default: HookErrorModeContinue)
	// Controls whether errors cause early exit, silent ignoring, or just logging
	HookErrorMode HookErrorMode
}

RouterOptions contains configuration options for the Router

func DefaultRouterOptions ΒΆ

func DefaultRouterOptions() *RouterOptions

DefaultRouterOptions returns router options with sensible defaults

Directories ΒΆ

Path Synopsis
adapters
fiber
Package fiber provides a Fiber middleware adapter for authula.
Package fiber provides a Fiber middleware adapter for authula.
cmd
migrate command
examples
fiber command
Package main demonstrates mounting Authula in a Fiber application using the Fiber adapter.
Package main demonstrates mounting Authula in a Fiber application using the Fiber adapter.
plugins
jwt

Jump to

Keyboard shortcuts

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