Guides / Authentication

Authentication Overview

Authentication verifies the identity of a user or system. Effective authentication protects resources from unauthorized access.

1. Password‑Based Authentication

Use strong, salted, and hashed passwords. Never store plaintext.

const bcrypt = require('bcrypt');

async function hashPassword(plain) {
    const salt = await bcrypt.genSalt(12);
    return await bcrypt.hash(plain, salt);
}

async function verifyPassword(plain, hash) {
    return await bcrypt.compare(plain, hash);
}

2. OAuth 2.0 & OpenID Connect

Delegate authentication to trusted providers (Google, GitHub, etc.).

<a href="https://accounts.google.com/o/oauth2/v2/auth?
client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&response_type=code
&scope=openid%20email%20profile"
   class="auth-button">Sign in with Google</a>

3. JSON Web Tokens (JWT)

Stateless authentication using signed tokens.

const jwt = require('jsonwebtoken');

function sign(payload) {
    return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1h' });
}

function verify(token) {
    try {
        return jwt.verify(token, process.env.JWT_SECRET);
    } catch (e) {
        return null;
    }
}

4. Multi‑Factor Authentication (MFA)

Combine something you know (password) with something you have (OTP, authenticator app).

const speakeasy = require('speakeasy');

function generateSecret() {
    return speakeasy.generateSecret({ length: 20 });
}

function verifyToken(secret, token) {
    return speakeasy.totp.verify({
        secret,
        encoding: 'base32',
        token,
        window: 1
    });
}

5. Best Practices