oneauth

package module
v0.0.42 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: Apache-2.0 Imports: 0 Imported by: 3

README

OneAuth

A Go authentication library providing unified local and OAuth-based authentication with support for multiple authentication methods per user account.

Features

  • Unified authentication — Password and OAuth through a single interface
  • Multi-provider support — One account accessible via password, Google, GitHub, etc.
  • API authentication — JWT access tokens, refresh tokens, API keys
  • Multi-tenant JWT — KeyStore interface for per-client signing keys with algorithm confusion prevention
  • Federated auth — App registration, resource-scoped token minting, custom claims
  • Flexible storage — File-based, GORM (SQL), and GAE/Datastore implementations
  • Client SDK — Token management, auto-refresh, credential persistence for CLI tools
  • gRPC support — Auth context utilities and interceptors

Quick Start

go get github.com/panyam/oneauth
import (
    "github.com/panyam/oneauth"
    "github.com/panyam/oneauth/stores/fs"
)

// Initialize stores
storagePath := "/path/to/storage"
userStore := fs.NewFSUserStore(storagePath)
identityStore := fs.NewFSIdentityStore(storagePath)
channelStore := fs.NewFSChannelStore(storagePath)
tokenStore := fs.NewFSTokenStore(storagePath)

// Create authentication callbacks
createUser := oneauth.NewCreateUserFunc(userStore, identityStore, channelStore)
validateCreds := oneauth.NewCredentialsValidator(identityStore, channelStore, userStore)

// Configure local authentication
localAuth := &oneauth.LocalAuth{
    CreateUser:          createUser,
    ValidateCredentials: validateCreds,
    EmailSender:         &oneauth.ConsoleEmailSender{},
    TokenStore:          tokenStore,
    BaseURL:             "https://yourapp.com",
    HandleUser:          yourSessionHandler,
}

// Set up HTTP routes
mux := http.NewServeMux()
mux.Handle("/auth/login", localAuth)
mux.Handle("/auth/signup", http.HandlerFunc(localAuth.HandleSignup))

See Getting Started for the full setup guide.

Architecture

OneAuth separates authentication into three layers:

User: john@example.com
├── Identity: john@example.com (verified)
├── Channel: local    (password hash)
├── Channel: google   (OAuth tokens)
└── Channel: github   (OAuth tokens)
  • User — A unique account with profile information
  • Identity — An email or phone number with verification status (shared across channels)
  • Channel — An authentication mechanism storing provider-specific credentials

Verifying an email through any channel (e.g., Google OAuth) verifies it for all channels.

See Architecture for design decisions, data model diagrams, and token lifecycle.

API Authentication

Protect API endpoints with JWT middleware:

middleware := &oneauth.APIMiddleware{
    KeyStore:        keyStore,        // multi-tenant (per-client keys)
    TokenQueryParam: "token",         // ?token= fallback for WebSocket clients
}

mux.Handle("/api/data", middleware.ValidateToken(handler))
mux.Handle("/api/write", middleware.RequireScopes("write")(handler))
mux.Handle("/api/public", middleware.Optional(handler))

// Access claims in handlers
userID := oneauth.GetUserIDFromAPIContext(r.Context())
custom := oneauth.GetCustomClaimsFromContext(r.Context())

See API Authentication for JWT lifecycle, custom claims, multi-tenant validation, and middleware configuration.

Federated Auth (App Registration)

For systems where multiple applications register and mint scoped JWTs:

// Resource server validates tokens from any registered app
keyStore := gorm.NewGORMKeyStore(db)
middleware := &oneauth.APIMiddleware{KeyStore: keyStore}

// Apps register via admin API and mint tokens for their users
token, err := oneauth.MintResourceToken(clientID, clientSecret, userID, scopes, customClaims)

See Architecture — Federated Auth for the full flow.

Store Implementations

Implementation Package Use Case
File-based stores/fs Development, < 1000 users
GORM (SQL) stores/gorm PostgreSQL, MySQL, SQLite
GAE/Datastore stores/gae Google Cloud deployments

All stores implement the same interfaces: UserStore, IdentityStore, ChannelStore, TokenStore, RefreshTokenStore, APIKeyStore, KeyStore.

See Stores for interface definitions and usage examples.

Client SDK

For CLI tools and programmatic clients:

import (
    "github.com/panyam/oneauth/client"
    "github.com/panyam/oneauth/client/stores/fs"
)

store, _ := fs.NewFSCredentialStore("", "myapp")
authClient := client.NewAuthClient("https://api.example.com", store)
authClient.Login("user@example.com", "password", "read write")

// Auto-refresh on 401 or before expiry
resp, _ := authClient.HTTPClient().Get("https://api.example.com/resource")

Documentation

Guides
Guide Description
Getting Started Installation, store setup, first auth flow
API Authentication JWT middleware, custom claims, multi-tenant validation
Browser Authentication OAuth flows, channel linking, session management
gRPC Integration Context utilities, auth interceptors
Stores Store interfaces, implementations, KeyStore
Testing Test patterns, security best practices
Reference
Document Description
Architecture Design decisions, data model, token lifecycle, federated auth
Auth Flows Login/signup decision trees, user journeys
Developer Guide Index of all developer documentation
User Guide End-user documentation
Release Notes Version history and changelog
API Docs Generated godoc reference

Requirements

  • Go 1.21+
  • golang.org/x/crypto/bcrypt — password hashing
  • github.com/golang-jwt/jwt/v5 — JWT tokens
  • golang.org/x/oauth2 — OAuth providers (optional)
  • gorm.io/gorm — GORM stores (optional)
  • cloud.google.com/go/datastore — GAE stores (optional)

License

See LICENSE file for terms and conditions.

Documentation

Overview

Package oneauth provides a unified authentication framework for Go applications.

OneAuth is organized into subpackages:

  • core/ — Foundation types: User, Identity, Channel, store interfaces, tokens, credentials, scopes
  • keys/ — Key storage, KID tracking, JWKS serving/fetching, encrypted key storage
  • admin/ — Admin auth, app registration API, resource token minting
  • apiauth/ — API token auth (JWT + API keys), validation middleware
  • localauth/ — Local username/password auth: signup, login, email verify, password reset
  • httpauth/ — HTTP middleware, CSRF protection, session-based auth mux
  • stores/ — Storage backends: fs/, gorm/, gae/
  • utils/ — Crypto helpers (PEM, JWK, key generation)
  • client/ — Client SDK
  • oauth2/ — OAuth2 provider implementations
  • grpc/ — gRPC auth interceptors

See each subpackage's SUMMARY.md for details.

Directories

Path Synopsis
Package client provides client-side authentication utilities for oneauth.
Package client provides client-side authentication utilities for oneauth.
stores/fs
Package fs provides a file system-based credential store for oneauth client.
Package fs provides a file system-based credential store for oneauth client.
cmd
oneauth module
Package core provides the foundation types and interfaces for the OneAuth authentication framework.
Package core provides the foundation types and interfaces for the OneAuth authentication framework.
grpc module
Package keystoretest provides shared test suites for all KeyStore implementations.
Package keystoretest provides shared test suites for all KeyStore implementations.
oauth2 module
saml module
stores
fs
gae module
gorm module

Jump to

Keyboard shortcuts

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