2.5 Hours

9. Permissions & Authorization Strategies

Authorization

Beyond roles, modern applications need fine-grained control over what users can do. This module covers permission-based authorization, hierarchical permissions, and policy-based access control.

What is a Permission?

A permission is the smallest unit of authorization. It answers: "Can this user perform this specific action on this specific resource?"

Text
Permission Format: resource:action

Examples:
user:create     - Can create new users
user:read       - Can view user profiles
user:update     - Can edit user information
user:delete     - Can remove users
post:publish    - Can publish blog posts
post:archive    - Can archive posts
comment:moderate - Can delete others' comments
Think of permissions as verbs (actions) on nouns (resources). This makes authorization logic consistent across your application.

Checking Permissions (Node.js)

Here is a simple permission check middleware.

JavaScript
function requirePermission(permission) {
    return (req, res, next) => {
        const userPermissions = req.user.permissions;

        if (userPermissions.includes(permission)) {
            next();
        } else {
            res.status(403).json({
                error: 'Forbidden',
                message: `Missing required permission: ${permission}`
            });
        }
    };
}

// Usage
app.post('/api/users', requirePermission('user:create'), createUser);
app.put('/api/posts/:id', requirePermission('post:update'), updatePost);
app.delete('/api/users/:id', requirePermission('user:delete'), deleteUser);

Requiring Multiple Permissions

Sometimes a user needs multiple permissions. Here are AND and OR logic examples.

JavaScript
// AND: User needs ALL permissions
function requireAllPermissions(permissions) {
    return (req, res, next) => {
        const userPermissions = req.user.permissions;
        const hasAll = permissions.every(p => userPermissions.includes(p));

        if (hasAll) {
            next();
        } else {
            res.status(403).json({ error: 'Insufficient permissions' });
        }
    };
}

// OR: User needs ANY of the permissions
function requireAnyPermission(permissions) {
    return (req, res, next) => {
        const userPermissions = req.user.permissions;
        const hasAny = permissions.some(p => userPermissions.includes(p));

        if (hasAny) {
            next();
        } else {
            res.status(403).json({ error: 'Insufficient permissions' });
        }
    };
}

// Example: Admin panel needs user:read AND user:write AND post:moderate
app.get('/api/admin', requireAllPermissions(['user:read', 'user:write', 'post:moderate']), adminDashboard);

// Example: File upload can use S3 OR local storage
app.post('/api/upload', requireAnyPermission(['storage:s3', 'storage:local']), uploadFile);

Hierarchical Permissions (Wildcards)

Wildcards allow parent permissions to imply child permissions. This simplifies permission management.

Text
user:*        → Implies user:create, user:read, user:update, user:delete
post:*        → Implies all post permissions
*:*           → Super admin (all permissions)

Example: A user with 'post:*' can create, read, update, and delete posts.
JavaScript
function hasPermission(userPermissions, requiredPermission) {
    const [resource, action] = requiredPermission.split(':');

    // Exact match
    if (userPermissions.includes(requiredPermission)) return true;

    // Resource wildcard (post:*)
    if (userPermissions.includes(`${resource}:*`)) return true;

    // Super admin (*:*)
    if (userPermissions.includes('*:*')) return true;

    return false;
}

// Example user permissions
const userPerms = ['post:*', 'user:read'];

console.log(hasPermission(userPerms, 'post:create'));  // true (inherited from post:*)
console.log(hasPermission(userPerms, 'post:delete'));  // true (inherited from post:*)
console.log(hasPermission(userPerms, 'user:update'));  // false (only user:read)
console.log(hasPermission(userPerms, 'user:delete'));  // false

Permission Caching

Checking permissions on every request can be expensive. Cache them with Redis.

JavaScript
class PermissionCache {
    constructor(redisClient, ttl = 300) {  // 5 minutes default
        this.redis = redisClient;
        this.ttl = ttl;
    }

    async getUserPermissions(userId) {
        const cacheKey = `perms:user:${userId}`;

        // Try cache first
        const cached = await this.redis.get(cacheKey);
        if (cached) {
            return JSON.parse(cached);
        }

        // Cache miss - load from database
        const permissions = await this.loadPermissionsFromDB(userId);

        // Store in cache
        await this.redis.setex(cacheKey, this.ttl, JSON.stringify(permissions));

        return permissions;
    }

    async invalidateUserPermissions(userId) {
        await this.redis.del(`perms:user:${userId}`);
    }
}

// When permissions change, invalidate cache
await permissionCache.invalidateUserPermissions(userId);
Performance Tip: Cache permissions for 5-15 minutes. Invalidate cache when roles/permissions change.

Knowledge Check

Ready to test your understanding of 9. Permissions & Authorization Strategies?

Back