lokstraauth

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README ΒΆ

Lokstra Auth

Modular Authentication and Authorization framework for Lokstra.

πŸ“– Overview

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.

πŸ—οΈ Architecture: 4 Layers

Lokstra Auth divides the authentication and authorization process into 4 independent layers:

1. Credential Layer (01_credential/) βœ… COMPLETE

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

2. Token Layer (02_token/) βœ… COMPLETE

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

3. Subject Layer (03_subject/) βœ… COMPLETE

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

4. Authorization Layer (04_authz/) βœ… COMPLETE

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

πŸš€ Quick Start

Installation
go get github.com/primadi/lokstra-auth
Simple Example: Complete Authentication Flow
package 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)
}
More Examples

See examples/ directory for complete working examples:

πŸ“ Detailed Examples

Basic Authentication Example
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)
}
OAuth2 Authentication Example
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)
    // ...
}
Passwordless Authentication Example
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, "user@example.com", "user123", "https://myapp.com")
// Email sent with magic link

// Verify magic link token
creds := &passwordless.Credentials{
    Email:     "user@example.com",
    Token:     "token-from-email",
    TokenType: passwordless.TokenTypeMagicLink,
}

result, err := auth.Authenticate(ctx, creds)
API Key Authentication Example
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"]
    // ...
}

πŸ“¦ Project Structure

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

πŸ“š Documentation

Layer Documentation
Examples

✨ Features

Credential Layer (01_credential/)
  • βœ… 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
Token Layer (02_token/)
  • βœ… 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
Subject Layer (03_subject/)
  • βœ… 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
Authorization Layer (04_authz/)
  • βœ… 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
Integration
  • βœ… Modular design - use any layer independently
  • βœ… Composable - combine layers as needed
  • βœ… Production-ready implementations
  • βœ… Comprehensive examples
  • βœ… Complete documentation

πŸ” Security Features

  1. Password Security

    • Bcrypt hashing (cost factor 10)
    • Constant-time comparison
  2. Token Security

    • JWT with HS256/RS256
    • Configurable expiration
    • Refresh token rotation
  3. API Key Security

    • SHA3-256 hashing
    • One-time display
    • Constant-time comparison
    • Automatic expiry checking
  4. Passwordless Security

    • One-time use tokens
    • Time-based expiration
    • Cryptographically secure random generation
    • Automatic cleanup
  5. OAuth2 Security

    • Token validation with provider
    • Email verification checking
    • HTTPS-only in production
  6. Passkey Security

    • WebAuthn/FIDO2 standard compliance
    • Public key cryptography
    • Phishing-resistant authentication

πŸ§ͺ Testing

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

🎯 Design Principles

  1. Modularity - Each layer can be used independently
  2. Composability - Layers can be combined as needed
  3. Extensibility - Easy to add new providers or strategies
  4. Type Safety - Leveraging Go interfaces for type-safe operations
  5. Lokstra Integration - Built on top of Lokstra Framework
  6. Production Ready - Following security best practices
  7. Developer Friendly - Clear APIs and comprehensive documentation

πŸ“‹ Requirements

πŸ—ΊοΈ Roadmap

Layer 1: Credential βœ…
  • 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
Layer 2: Token βœ…
  • JWT token manager
  • Access + Refresh token support
  • Simple token manager
  • Token store implementation
  • Complete documentation
  • Working examples
Layer 3: Subject βœ…
  • Simple subject resolver
  • Enriched resolver with external data
  • Cached resolver for performance
  • Identity store implementation
  • Identity context builder
  • Complete documentation
  • Working examples
Layer 4: Authorization βœ…
  • 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
Integration βœ…
  • Complete 4-layer examples
  • Multi-credential demo
  • Comprehensive documentation
  • Auth runtime orchestrator
  • Builder API
  • Lokstra middleware
  • Testing utilities
  • Benchmark suite

πŸ“„ License

See LICENSE file for details.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.


Built with ❀️ using Lokstra Framework

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	ErrNoAuthenticator         = errors.New("no authenticator configured")
	ErrNoTokenManager          = errors.New("no token manager configured")
	ErrNoSubjectResolver       = errors.New("no subject resolver configured")
	ErrNoContextBuilder        = errors.New("no identity context builder configured")
	ErrNoAuthorizer            = errors.New("no authorizer configured")
	ErrAuthenticationFailed    = errors.New("authentication failed")
	ErrTokenGenerationFailed   = errors.New("token generation failed")
	ErrSubjectResolutionFailed = errors.New("subject resolution failed")
	ErrAuthorizationFailed     = errors.New("authorization check failed")
)

Functions ΒΆ

This section is empty.

Types ΒΆ

type Auth ΒΆ

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

Auth is the main runtime object for Lokstra Auth framework It orchestrates all 4 layers and provides a unified API

func New ΒΆ

func New(config *Config) *Auth

New creates a new Auth runtime instance

func (*Auth) Authorize ΒΆ

Authorize checks if a subject is authorized to perform an action on a resource Layer 4

func (*Auth) CheckPermission ΒΆ

func (a *Auth) CheckPermission(ctx context.Context, identity *subject.IdentityContext, permission string) (bool, error)

CheckPermission is a convenience method to check a simple permission

func (*Auth) CheckRole ΒΆ

func (a *Auth) CheckRole(ctx context.Context, identity *subject.IdentityContext, role string) (bool, error)

CheckRole is a convenience method to check if identity has a role

func (*Auth) GetAuthorizer ΒΆ

func (a *Auth) GetAuthorizer() authz.Authorizer

GetAuthorizer returns the configured authorizer

func (*Auth) Login ΒΆ

func (a *Auth) Login(ctx context.Context, request *LoginRequest) (*LoginResponse, error)

Login performs the complete authentication flow Layer 1 -> Layer 2 -> Layer 3

func (*Auth) RegisterAuthenticator ΒΆ

func (a *Auth) RegisterAuthenticator(authType string, authenticator credential.Authenticator)

RegisterAuthenticator registers an authenticator for a specific type

func (*Auth) SetAuthorizer ΒΆ

func (a *Auth) SetAuthorizer(authorizer authz.Authorizer)

SetAuthorizer sets the authorizer

func (*Auth) SetIdentityContextBuilder ΒΆ

func (a *Auth) SetIdentityContextBuilder(builder subject.IdentityContextBuilder)

SetIdentityContextBuilder sets the identity context builder

func (*Auth) SetSubjectResolver ΒΆ

func (a *Auth) SetSubjectResolver(resolver subject.SubjectResolver)

SetSubjectResolver sets the subject resolver

func (*Auth) SetTokenManager ΒΆ

func (a *Auth) SetTokenManager(manager token.TokenManager)

SetTokenManager sets the token manager

func (*Auth) Verify ΒΆ

func (a *Auth) Verify(ctx context.Context, request *VerifyRequest) (*VerifyResponse, error)

Verify verifies a token and optionally builds identity context Layer 2 -> Layer 3

type Builder ΒΆ

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

Builder provides a fluent API for building Auth runtime

func NewBuilder ΒΆ

func NewBuilder() *Builder

NewBuilder creates a new Auth builder

func (*Builder) AddMetadata ΒΆ

func (b *Builder) AddMetadata(key string, value interface{}) *Builder

AddMetadata adds metadata to the configuration

func (*Builder) Build ΒΆ

func (b *Builder) Build() *Auth

Build returns the configured Auth instance

func (*Builder) DisableRefreshToken ΒΆ

func (b *Builder) DisableRefreshToken() *Builder

DisableRefreshToken disables refresh token generation

func (*Builder) DisableSessionManagement ΒΆ

func (b *Builder) DisableSessionManagement() *Builder

DisableSessionManagement disables session management

func (*Builder) EnableRefreshToken ΒΆ

func (b *Builder) EnableRefreshToken() *Builder

EnableRefreshToken enables refresh token generation

func (*Builder) EnableSessionManagement ΒΆ

func (b *Builder) EnableSessionManagement() *Builder

EnableSessionManagement enables session management

func (*Builder) SetDefaultAuthenticator ΒΆ

func (b *Builder) SetDefaultAuthenticator(authType string) *Builder

SetDefaultAuthenticator sets the default authenticator type

func (*Builder) WithAuthenticator ΒΆ

func (b *Builder) WithAuthenticator(authType string, authenticator credential.Authenticator) *Builder

WithAuthenticator registers an authenticator

func (*Builder) WithAuthorizer ΒΆ

func (b *Builder) WithAuthorizer(authorizer authz.Authorizer) *Builder

WithAuthorizer sets the authorizer

func (*Builder) WithConfig ΒΆ

func (b *Builder) WithConfig(config *Config) *Builder

WithConfig sets a custom configuration

func (*Builder) WithIdentityContextBuilder ΒΆ

func (b *Builder) WithIdentityContextBuilder(builder subject.IdentityContextBuilder) *Builder

WithIdentityContextBuilder sets the identity context builder

func (*Builder) WithSubjectResolver ΒΆ

func (b *Builder) WithSubjectResolver(resolver subject.SubjectResolver) *Builder

WithSubjectResolver sets the subject resolver

func (*Builder) WithTokenManager ΒΆ

func (b *Builder) WithTokenManager(manager token.TokenManager) *Builder

WithTokenManager sets the token manager

type Config ΒΆ

type Config struct {
	// DefaultAuthenticatorType is the default authenticator to use
	DefaultAuthenticatorType string

	// IssueRefreshToken indicates whether to issue refresh tokens
	IssueRefreshToken bool

	// SessionManagement indicates whether to manage sessions
	SessionManagement bool

	// Metadata contains additional runtime metadata
	Metadata map[string]any
}

Config holds the configuration for Auth runtime

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns a default configuration

type LoginRequest ΒΆ

type LoginRequest struct {
	// Credentials contains the credentials to authenticate
	Credentials credential.Credentials

	// Metadata contains additional request metadata
	Metadata map[string]any
}

LoginRequest represents a login request

type LoginResponse ΒΆ

type LoginResponse struct {
	// AccessToken is the issued access token
	AccessToken *token.Token

	// RefreshToken is the issued refresh token (if enabled)
	RefreshToken *token.Token

	// Identity is the resolved identity context
	Identity *subject.IdentityContext

	// Metadata contains additional response metadata
	Metadata map[string]any
}

LoginResponse represents a login response

type VerifyRequest ΒΆ

type VerifyRequest struct {
	// Token is the token to verify
	Token string

	// BuildIdentityContext indicates whether to build full identity context
	BuildIdentityContext bool

	// Metadata contains additional request metadata
	Metadata map[string]any
}

VerifyRequest represents a token verification request

type VerifyResponse ΒΆ

type VerifyResponse struct {
	// Valid indicates whether the token is valid
	Valid bool

	// Claims contains the extracted claims
	Claims token.Claims

	// Identity is the resolved identity context (if requested)
	Identity *subject.IdentityContext

	// Metadata contains additional response metadata
	Metadata map[string]any
}

VerifyResponse represents a token verification response

Jump to

Keyboard shortcuts

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