Modular Authentication and Authorization framework for Lokstra.
Lokstra Auth is a modular authentication and authorization framework built on top of Lokstra Framework. Designed with a 4-layer architecture that enables high flexibility and composability.
Lokstra Auth divides the authentication and authorization process into 4 independent layers:
The first layer is responsible for receiving and validating credentials from various sources:
- β Basic Auth - Username/password with bcrypt
- β OAuth2 - Google, GitHub, Facebook integration
- β Passwordless - Magic Link and OTP via email
- β API Key - Key-based authentication with SHA3-256 hashing
- β Passkey - WebAuthn/FIDO2 support
Status: Production ready with 5 authenticator types Documentation: 01_credential/README.md
The second layer manages token lifecycle and data extraction:
- β JWT Manager - Access + Refresh token with rotation
- β Simple Token - Opaque token management
- β Token Store - In-memory token storage for testing
- β Claim extraction and validation
- β Custom token formats
Status: Production ready with 2 token manager types Documentation: 02_token/README.md
The third layer transforms claims into complete identity context:
- β Simple Resolver - Direct claim to identity mapping
- β Enriched Resolver - Identity enrichment with external data
- β Cached Resolver - Performance optimization with caching
- β Identity Store - In-memory user data storage
- β Role and permission loading
- β Multi-source data aggregation
Status: Production ready with 3 resolver types Documentation: 03_subject/README.md
The fourth layer performs access evaluation and policy enforcement:
- β RBAC - Role-Based Access Control with wildcard support
- β ABAC - Attribute-Based Access Control with rules
- β ACL - Resource-level Access Control Lists
- β Policy-Based - Flexible policy evaluation with combining algorithms
- β Resource-level permissions
- β Thread-safe implementations
Status: Production ready with 4 authorization models Documentation: 04_authz/README.md
go get github.com/primadi/lokstra-authpackage main
import (
"context"
"fmt"
"log"
"github.com/primadi/lokstra-auth/01_credential/basic"
"github.com/primadi/lokstra-auth/02_token/jwt"
"github.com/primadi/lokstra-auth/03_subject/simple"
authz "github.com/primadi/lokstra-auth/04_authz"
"github.com/primadi/lokstra-auth/04_authz/rbac"
)
func main() {
ctx := context.Background()
// Layer 1: Setup authentication
userProvider := basic.NewInMemoryUserProvider()
passwordHash, _ := basic.HashPassword("MySecure@Pass123")
userProvider.AddUser(&basic.User{
ID: "user-001",
Username: "john.doe",
PasswordHash: passwordHash,
})
validator := basic.NewValidator(basic.DefaultValidatorConfig())
authenticator := basic.NewAuthenticator(userProvider, validator)
// Layer 2: Setup token management
jwtConfig := jwt.DefaultConfig("your-secret-key")
tokenManager := jwt.NewManager(jwtConfig)
// Layer 3: Setup subject resolution
resolver := simple.NewResolver()
roleProvider := simple.NewStaticRoleProvider(map[string][]string{
"user-001": {"admin", "user"},
})
contextBuilder := simple.NewContextBuilder(
roleProvider,
simple.NewStaticPermissionProvider(map[string][]string{}),
simple.NewStaticGroupProvider(map[string][]string{}),
simple.NewStaticProfileProvider(map[string]map[string]any{}),
)
// Layer 4: Setup authorization
rbacEvaluator := rbac.NewEvaluator(map[string][]string{
"admin": {"*"}, // Admin has all permissions
"user": {"read:posts", "create:posts"},
})
// Use it!
// 1. Authenticate
authResult, _ := authenticator.Authenticate(ctx, &basic.BasicCredentials{
Username: "john.doe",
Password: "MySecure@Pass123",
})
fmt.Println("β
Authenticated:", authResult.Subject)
// 2. Generate token
token, _ := tokenManager.Generate(ctx, authResult.Claims)
fmt.Println("β
Token generated")
// 3. Verify token
verifyResult, _ := tokenManager.Verify(ctx, token.Value)
fmt.Println("β
Token verified")
// 4. Build identity
subject, _ := resolver.Resolve(ctx, verifyResult.Claims)
identity, _ := contextBuilder.Build(ctx, subject)
fmt.Println("β
Identity built, Roles:", identity.Roles)
// 5. Check authorization
decision, _ := rbacEvaluator.Evaluate(ctx, &authz.AuthorizationRequest{
Subject: identity,
Resource: &authz.Resource{Type: "posts", ID: "123"},
Action: authz.ActionRead,
})
fmt.Println("β
Authorization:", decision.Allowed)
}See examples/ directory for complete working examples:
- Basic Flow: examples/complete/01_basic_flow/
- Multi-Credential: examples/complete/02_multi_auth/
import (
"github.com/primadi/lokstra-auth/01_credential/basic"
)
// Create authenticator
userStore := basic.NewInMemoryUserStore()
auth := basic.NewAuthenticator(&basic.Config{
UserStore: userStore,
})
// Register user
hashedPassword, _ := basic.HashPassword("mypassword")
userStore.AddUser(&basic.User{
ID: "user123",
Username: "john",
Password: hashedPassword,
})
// Authenticate
creds := &basic.Credentials{
Username: "john",
Password: "mypassword",
}
result, err := auth.Authenticate(ctx, creds)
if result.Success {
fmt.Println("Logged in as:", result.Subject)
}import (
"github.com/primadi/lokstra-auth/01_credential/oauth2"
)
// Create OAuth2 authenticator
auth := oauth2.NewAuthenticator(nil) // Uses default providers
// Authenticate with Google access token
creds := &oauth2.Credentials{
Provider: oauth2.ProviderGoogle,
AccessToken: "ya29.a0AfH6SMBxxxxx...",
}
result, err := auth.Authenticate(ctx, creds)
if result.Success {
email := result.Claims["email"].(string)
name := result.Claims["name"].(string)
// ...
}import (
"github.com/primadi/lokstra-auth/01_credential/passwordless"
)
// Create passwordless authenticator
auth := passwordless.NewAuthenticator(&passwordless.Config{
TokenStore: passwordless.NewInMemoryTokenStore(),
UserResolver: myUserResolver,
TokenSender: myEmailSender,
})
// Request magic link
err := auth.InitiateMagicLink(ctx, "[email protected]", "user123", "https://myapp.com")
// Email sent with magic link
// Verify magic link token
creds := &passwordless.Credentials{
Email: "[email protected]",
Token: "token-from-email",
TokenType: passwordless.TokenTypeMagicLink,
}
result, err := auth.Authenticate(ctx, creds)import (
"github.com/primadi/lokstra-auth/01_credential/apikey"
)
// Create API key authenticator
keyStore := apikey.NewInMemoryKeyStore()
auth := apikey.NewAuthenticator(&apikey.Config{
KeyStore: keyStore,
})
// Generate API key
expiresIn := 30 * 24 * time.Hour
keyString, apiKey, err := auth.GenerateKey(
ctx,
"user123", // User ID
"Production API Key", // Key name
[]string{"read", "write"}, // Scopes
&expiresIn,
)
// Authenticate with API key
creds := &apikey.Credentials{
APIKey: keyString,
}
result, err := auth.Authenticate(ctx, creds)
if result.Success {
scopes := result.Claims["scopes"]
// ...
}lokstra-auth/
βββ 01_credential/ # β
Layer 1: Credential Input (COMPLETE)
β βββ contract.go # Core interfaces
β βββ basic/ # Username/password
β βββ oauth2/ # OAuth2 (Google, GitHub, Facebook)
β βββ passwordless/ # Magic Link & OTP
β βββ apikey/ # API key authentication
β βββ README.md # β
Complete documentation
βββ 02_token/ # β
Layer 2: Token Verification (COMPLETE)
β βββ contract.go # Core interfaces
β βββ jwt/ # JWT with access+refresh tokens
β βββ simple/ # Simple token manager
β βββ README.md # β
Complete documentation
βββ 03_subject/ # β
Layer 3: Subject Resolution (COMPLETE)
β βββ contract.go # Interface definitions
β βββ simple/ # Simple resolver
β βββ enriched/ # Enriched resolver with external data
β βββ cached/ # Cached resolver for performance
β βββ README.md # β
Complete documentation
βββ 04_authz/ # β
Layer 4: Authorization (COMPLETE)
β βββ contract.go # Interface definitions
β βββ rbac/ # Role-based access control
β βββ abac/ # Attribute-based access control
β βββ acl/ # Access control lists
β βββ policy/ # Policy-based authorization
β βββ README.md # β
Complete documentation
βββ middleware/ # β
Lokstra Framework Integration
β βββ auth.go # Token verification middleware
β βββ permission.go # Permission check middleware
β βββ role.go # Role check middleware
βββ examples/ # β
Working Examples
β βββ 01_credential/ # Credential layer examples
β β βββ 01_basic/ # Basic auth flow
β β βββ 02_multi_auth/ # Multi-authenticator
β β βββ 03_oauth2/ # β
OAuth2 example
β β βββ 04_passwordless/# β
Passwordless example
β β βββ 05_apikey/ # β
API Key example
β βββ 02_token/ # β
Token layer examples
β βββ 03_subject/ # β
Subject layer examples
β βββ 04_authz/ # β
Authorization layer examples
β β βββ 01_rbac/ # RBAC examples
β β βββ 02_abac/ # ABAC examples
β β βββ 03_acl/ # ACL examples
β βββ complete/ # Complete 4-layer integration
β βββ 01_basic_flow/ # Basic authentication flow
β βββ 02_multi_auth/ # Multi-credential demo
βββ README.md # This file
- β Layer 1: Credential - Complete - Basic, OAuth2, Passwordless, API Key
- β Layer 2: Token - Complete - JWT (Access+Refresh), Simple, Store
- β Layer 3: Subject - Complete - Simple, Enriched, Cached resolvers
- β Layer 4: Authorization - Complete - RBAC, ABAC, ACL, Policy-based
- β Basic Authentication - Username/password flow
- β Multi-Authenticator - Multiple auth methods
- β OAuth2 Auth - Provider integration guide
- β Passwordless Auth - Magic Link & OTP
- β API Key Auth - Full API key lifecycle
- β JWT Token Management - Access & refresh tokens
- β Subject Resolution - Identity enrichment & caching
- β Authorization Examples - RBAC, ABAC, ACL examples
- β Complete Flow - All 4 layers integrated
- β Multi-Credential Demo - Multiple auth methods with RBAC
- β 5 Authenticator Types: Basic, OAuth2, Passwordless, API Key, Passkey
- β Provider Support: Google, GitHub, Facebook OAuth2
- β Passwordless Methods: Magic Link (15min TTL), OTP (5min TTL)
- β API Key Features: SHA3-256 hashing, scopes, expiry, revocation
- β Passkey Support: WebAuthn/FIDO2 authentication
- β Multi-Authenticator: Handle multiple auth methods simultaneously
- β Extensible: Custom authenticators via interface
- β In-Memory Stores: Testing-ready implementations
- β JWT generation with access + refresh tokens
- β Automatic token rotation
- β Token verification and validation
- β Simple opaque token management
- β Token store for testing
- β Configurable token expiry
- β Custom claims support
- β Simple subject resolver (direct mapping)
- β Enriched resolver (external data integration)
- β Cached resolver (performance optimization)
- β Identity store for user data
- β User/subject resolution from tokens
- β Identity context building
- β Claims enrichment with roles, permissions, profile
- β Multi-source data aggregation
- β Role-Based Access Control (RBAC) with wildcards
- β Attribute-Based Access Control (ABAC) with conditional rules
- β Access Control Lists (ACL) for fine-grained permissions
- β Policy-based authorization with multiple combining algorithms
- β Permission and role checking helpers
- β Resource-level access control
- β Thread-safe implementations
- β Flexible policy evaluation
- β Modular design - use any layer independently
- β Composable - combine layers as needed
- β Production-ready implementations
- β Comprehensive examples
- β Complete documentation
-
Password Security
- Bcrypt hashing (cost factor 10)
- Constant-time comparison
-
Token Security
- JWT with HS256/RS256
- Configurable expiration
- Refresh token rotation
-
API Key Security
- SHA3-256 hashing
- One-time display
- Constant-time comparison
- Automatic expiry checking
-
Passwordless Security
- One-time use tokens
- Time-based expiration
- Cryptographically secure random generation
- Automatic cleanup
-
OAuth2 Security
- Token validation with provider
- Email verification checking
- HTTPS-only in production
-
Passkey Security
- WebAuthn/FIDO2 standard compliance
- Public key cryptography
- Phishing-resistant authentication
Each layer comes with in-memory implementations for testing:
// Basic Auth testing
userStore := basic.NewInMemoryUserStore()
userStore.AddUser(&basic.User{...})
// Passwordless testing
tokenStore := passwordless.NewInMemoryTokenStore()
// API Key testing
keyStore := apikey.NewInMemoryKeyStore()
// Run examples
go run examples/01_credential/05_apikey/main.go
go run examples/01_credential/04_passwordless/main.go
go run examples/complete/02_multi_auth/main.go- Modularity - Each layer can be used independently
- Composability - Layers can be combined as needed
- Extensibility - Easy to add new providers or strategies
- Type Safety - Leveraging Go interfaces for type-safe operations
- Lokstra Integration - Built on top of Lokstra Framework
- Production Ready - Following security best practices
- Developer Friendly - Clear APIs and comprehensive documentation
- Go 1.21 or higher
- Lokstra Framework v0.3.4+
- Basic authenticator
- OAuth2 authenticator (Google, GitHub, Facebook)
- Passwordless authenticator (Magic Link, OTP)
- API Key authenticator
- Passkey/WebAuthn authenticator
- Multi-authenticator support
- Complete documentation
- Working examples
- JWT token manager
- Access + Refresh token support
- Simple token manager
- Token store implementation
- Complete documentation
- Working examples
- Simple subject resolver
- Enriched resolver with external data
- Cached resolver for performance
- Identity store implementation
- Identity context builder
- Complete documentation
- Working examples
- RBAC authorizer with wildcards
- ABAC authorizer with rules
- ACL manager for resource permissions
- Policy-based authorization
- Policy store implementation
- Multiple combining algorithms
- Complete documentation
- Working examples
- Complete 4-layer examples
- Multi-credential demo
- Comprehensive documentation
- Auth runtime orchestrator
- Builder API
- Lokstra middleware
- Testing utilities
- Benchmark suite
See LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
Built with β€οΈ using Lokstra Framework