A lightweight authentication library for Swift providing common authentication operations, such as password hashing and OTP verification and generation.
Add the Authentication package to your Package.swift dependencies:
dependencies: [
.package(url: "https://github.com/vapor/authentication.git", from: "4.0.0")
]Then add Authentication to your target's dependencies:
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "Authentication", package: "authentication")
]
)
]Securely hash and verify user passwords using the bcrypt algorithm or the PasswordHasher algorithm:
import Authentication
// Create a hasher with default cost (12)
let hasher = BcryptHasher()
// Or a hasher injected in
let hasher: PasswordHasher
// Hash a password
let hash = try hasher.hash("secretPassword123")
// Verify a password against a hash
let isValid = try hasher.verify("secretPassword123", created: hash)
// isValid == trueThe cost parameter controls how computationally expensive the hashing operation is. Higher costs provide more security but take longer to compute:
// Create a hasher with custom cost (valid range: 4-31)
let hasher = BcryptHasher(cost: 14)
let hash = try hasher.hash("myPassword")Note: Increasing the cost by 1 doubles the computation time. A cost of 12 takes approximately 250ms on modern hardware.
Generate RFC-compliant HOTP and TOTP codes for multi-factor authentication.
TOTP generates codes that change at regular intervals (typically 30 seconds):
import Authentication
import Crypto
// Create a symmetric key (store this securely per user)
let key = SymmetricKey(size: .bits256)
// Create a TOTP generator
let totp = TOTP(key: key, digest: .sha256)
// Generate a code for the current time
let code = totp.generate(time: Date())
print(code) // e.g., "482719"HOTP generates codes based on a counter value:
import Authentication
import Crypto
let key = SymmetricKey(size: .bits256)
// Create an HOTP generator
let hotp = HOTP(key: key, digest: .sha256)
// Generate codes for sequential counters
let code0 = hotp.generate(counter: 0)
let code1 = hotp.generate(counter: 1)Both HOTP and TOTP support configuration options:
// Configure digest algorithm: .sha1, .sha256, or .sha512
let totp = TOTP(key: key, digest: .sha512)
// Configure code length: .six, .seven, or .eight digits
let totp = TOTP(key: key, digest: .sha256, digits: .eight)
// Configure time interval (TOTP only, default: 30 seconds)
let totp = TOTP(key: key, digest: .sha256, interval: 60)To account for clock drift or user delays, generate multiple codes within a range:
let totp = TOTP(key: key, digest: .sha256)
// Generate codes for current time plus/minus 1 interval
let codes = totp.generate(time: Date(), range: 1)
// Returns 3 codes: [previous, current, next]
// Check if user's code matches any valid code
let isValid = codes.contains(userCode)