Installation
Configure Authula in your project.
There are two ways to configure Authula in your project: as a standalone server or as a library integrated into your existing API server.
The following sections will guide you through both methods.
Standalone Mode
Setup configuration file
- Make a copy of the following
config.tomlfile which provides you with some default configuration to get started:
# Application Name
app_name = "Authula"
# Base URL for the application (used as the base url of the API and for redirects, emails, etc.)
base_url = "http://localhost:8080"
# Base Path for API endpoints (e.g., "/auth")
base_path = "/auth"
# Used for encryption. Generate using `openssl rand -hex 32`.
# NOTE: It is recommended to set this via the AUTHULA_SECRET environment variable instead of hardcoding it here for better security.
# secret = ""
# Optional list of API routes to exclude from Authula's router.
disabled_paths = []
# -----------------------------------
# - Database Configuration
# -----------------------------------
[database]
provider = "postgres"
# NOTE: It is recommended to set the database URL via the AUTHULA_DATABASE_URL environment variable instead of hardcoding it here for better security.
# url = "postgresql://username:password@localhost:5432/authula?sslmode=disable"
max_open_conns = 25
max_idle_conns = 5
conn_max_lifetime = "10m"
# -----------------------------------
# - Logger Configuration
# -----------------------------------
[logger]
level = "debug" # Options: "debug", "info", "warn", "error"
# -----------------------------------
# - Session Configuration
# -----------------------------------
[session]
cookie_name = "authula.session_token"
expires_in = "24h"
update_age = "5m"
cookie_max_age = "24h"
secure = false
http_only = true
same_site = "lax" # Options: "lax", "strict", "none"
auto_cleanup = true # Flag to automatically clean up expired sessions and enforce max sessions per user
cleanup_interval = "1m" # Interval for automatic cleanup of expired sessions
max_sessions_per_user = 5 # Maximum number of concurrent sessions per user (0 = unlimited)
# -----------------------------------
# - Verification Configuration
# -----------------------------------
[verification]
auto_cleanup = true # Flag to automatically clean up expired verifications
cleanup_interval = "1m" # Interval for automatic cleanup of expired verifications
# -----------------------------------
# - Security Configuration
# -----------------------------------
[security]
trusted_origins = ["http://localhost:3000"]
trusted_headers = [] # e.g., ["X-Real-IP", "CF-Connecting-IP" (cloudflare), ...]
trusted_proxies = []
# IMPORTANT CORS NOTE: If using the session plugin, the CORS config below must specify exact allowed_origins.
# Setting allowed_origins = ["*"] with allow_credentials = true is NOT allowed by browsers and will fail.
# Example CORS configuration when using sessions:
# allow_credentials = true
# allowed_origins = ["http://localhost:3000"]
[security.cors]
allow_credentials = true
allowed_origins = ["http://localhost:3000"] # If using session plugin, specify exact origins instead of "*"
allowed_methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
# If using the CSRF plugin, ensure the CSRF token header is included here
allowed_headers = ["Authorization", "Content-Type", "Set-Cookie", "Cookie"]
exposed_headers = []
max_age = "24h"
# -----------------------------------
# - Event Bus Configuration
# -----------------------------------
# The event bus handles internal authentication events and allows plugins to communicate
# Supports multiple providers via Watermill.
# Provider options: "gochannel", "sqlite", "postgres", "redis", "kafka", "nats", "rabbitmq"
[event_bus]
# Optional prefix for all event topics (default: "")
prefix = ""
# Maximum concurrent handlers for event processing (default: 100)
max_concurrent_handlers = 100
# Timeout for async published events (default: 5s)
context_timeout = "5s"
# Options: "gochannel", "sqlite", "postgres", "redis", "kafka", "nats", "rabbitmq"
provider = "sqlite"
# GoChannel Configuration (Default - In-Memory)
# Best for development and testing - events lost on restart
# Other providers enable distributed event handling across multiple instances
[event_bus.go_channel]
buffer_size = 100
# SQLite Configuration
# Event storage in SQLite file (good for single-instance deployments with persistence)
# [event_bus.sqlite]
# db_path = "events.db" # File path for the SQLite database (relative to current working directory)
# Redis Configuration
# Enables distributed event handling across multiple instances
# [event_bus.redis]
# consumer_group = "authula_consumer_group"
# Kafka Configuration
# For high-throughput, distributed event streaming
# [event_bus.kafka]
# brokers = "localhost:9092"
# consumer_group = "authula_consumer_group"
# NATS Configuration
# Lightweight, cloud-native messaging
# [event_bus.nats]
# url = "nats://localhost:4222"
# AMQP Configuration (RabbitMQ)
# Traditional message broker with advanced routing
# [event_bus.rabbitmq]
# Prefer to use EVENT_BUS_RABBITMQ_URL environment variable to set the URL
# url = "amqp://guest:guest@localhost:5672/"
# -----------------------------------
# - Plugins Configuration
# -----------------------------------
[plugins]
# Check the plugins section of the documentation for details on configuring each plugin.- Feel free to modify the configuration fields with your desired settings. Most of these settings allow you to configure the server according to your needs.
- It is recommended that you do not set secret values within the
config.tomlfile directly. Instead, use environment variables to manage sensitive values securely.
Set environment variables via .env file
- Make a copy of the following environment variables into a
.envfile:
# Third party ENV variables
# Required for OAuth2 plugin
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
# Required depending on the plugin being used and their providers
POSTGRES_URL=
REDIS_URL=
KAFKA_BROKERS=
NATS_URL=
RABBITMQ_URL=
# Optional - Required only if using event bus consumers e.g. Redis/Kafka
EVENT_BUS_CONSUMER_GROUP=
# Authula ENV variables
# Path to your configuration file (e.g., ./config.toml) (optional as it defaults to looking for config.toml in the current working directory)
AUTHULA_CONFIG_PATH=
# The base URL of your API (e.g., http://localhost:8080) (optional as it can be set in config.toml)
AUTHULA_BASE_URL=
# Used for encryption. Generate using `openssl rand -hex 32` (required if not set in config.toml)
AUTHULA_SECRET=
# sqlite: "auth.db"
# postgresql: "postgresql://username:password@localhost:5432/authula?sslmode=disable"
# mysql: "username:password@tcp(localhost:3306)/authula"
# (required if not set in config.toml)
AUTHULA_DATABASE_URL=
GO_ENV=development
PORT=8080- Feel free to remove any environment variables you are not using or do not need for your setup.
Run the server via Docker
- You can run the server using Docker by mounting your configuration file and passing the necessary environment variables. Here's an example:
$ docker run -itd \
-p 8080:8080 \
-v ./config.toml:/home/appuser/config.toml \
--env-file ./.env \
ghcr.io/authula/authula:latest- Make sure to have the
config.tomland.envfiles in the same directory when you run the Docker command above.
Library Mode
Set environment variables
Follow the environment variables step from standalone mode above.
Install the Package
$ go get github.com/Authula/authulaCreate auth config
import (
authula "github.com/Authula/authula"
authulaconfig "github.com/Authula/authula/config"
)
config := authulaconfig.NewConfig(
/*
* the same options as config.toml can be set here via functional options.
* See the "config/options.go" file in the repository for all available options.
* e.g.:
authulaconfig.WithAppName("YourAppName"),
authulaconfig.WithBasePath("/api/auth"),
// ...other configuration options
*/
)
auth := authula.New(&authula.AuthConfig{
Config: config,
Plugins: [/*...*/],
})Configure database
Authula supports multiple database providers. You can select a database provider by supplying it in the config.
import (
authulaconfig "github.com/Authula/authula/config"
)
authulaconfig.NewConfig(
authulaconfig.WithDatabase(authulamodels.DatabaseConfig{
Provider: "sqlite",
}),
)Database migrations
Authula runs all migrations (core & plugins) automatically when you create a new instance of the library so all the relevant database tables are created for you without any additional steps. This is done via a custom migrator which utilises Bun ORM and raw SQL.
See the Database Schema for the core tables created by these migrations.
Authentication Methods
Configure the authentication methods you want to use by choosing from the available plugins. Authula supports various authentication methods, including the Email/Password authentication method as a plugin and also the OAuth2 plugin with providers such as Discord, GitHub and Google with more coming soon.
import (
authula "github.com/Authula/authula"
authulaconfig "github.com/Authula/authula/config"
emailpasswordplugin "github.com/Authula/authula/plugins/email-password"
emailpasswordplugintypes "github.com/Authula/authula/plugins/email-password/types"
)
config := authulaconfig.NewConfig(/*...*/)
auth := authula.New(&authula.AuthConfig{
Config: config,
Plugins: [
emailpasswordplugin.New(emailpasswordplugintypes.EmailPasswordPluginConfig{
Enabled: true,
// ...other configuration options
}),
],
})Mount Handlers
To handle API requests, you need to integrate the Authula handlers in your API.
This is an example of how it can be done with the standard library server:
import (
"log"
"net/http"
authula "github.com/Authula/authula"
authulaconfig "github.com/Authula/authula/config"
)
func main() {
// Initialise auth
config := authulaconfig.NewConfig(/*...*/)
auth := authula.New(&authula.AuthConfig{
Config: config,
Plugins: [/*...*/],
})
// Start the server and mount the handler
log.Fatal(http.ListenAndServe(":8080", auth.Handler()))
}Take a look at the Integrations section to see how to integrate it with other libraries.
