Skip to content

primadi/lokstra-auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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, "[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)

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

About

Authentication & Authorization framework for Lokstra

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages