🛡️ Authentication vs Authorization: Every Developer Needs to Know 🛡️
Sachin Gadekar
Posted on August 3, 2024
👋 Hello, Devs!
In today's post, we're diving into the crucial concepts of Authentication and Authorization. These terms are often used interchangeably but they serve different purposes in the security realm. Let’s break it down!
🔐 Authentication: Who Are You?
Authentication is the process of verifying the identity of a user or entity. Think of it as the gatekeeper asking, "Who are you?" Here are some common methods:
- Username and Password: The most common method.
- Two-Factor Authentication (2FA): Adds an extra layer of security.
- Biometric Verification: Uses fingerprints, facial recognition, etc.
- OAuth: Allows users to log in using another service (like Google, Facebook).
🛂 Authorization: What Are You Allowed to Do?
Authorization determines what resources a user can access. It happens after authentication. Think of it as the gatekeeper saying, "Okay, you’re in. Now, what can you do?"
- Role-Based Access Control (RBAC): Permissions are assigned to roles, and users are assigned roles.
- Attribute-Based Access Control (ABAC): Permissions are based on attributes (e.g., time of day, location).
- Access Control Lists (ACLs): Lists that tell what permissions each user has.
🛠️ Implementing Authentication in Code
Here’s a quick example using Node.js with Express and Passport.js:
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
const app = express();
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(passport.initialize());
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
🔧 Implementing Authorization in Code
Here's an example of RBAC in Express.js:
const roles = {
admin: ['create', 'read', 'update', 'delete'],
user: ['read']
};
function authorize(role, action) {
return (req, res, next) => {
if (roles[role].includes(action)) {
next();
} else {
res.status(403).send('Forbidden');
}
};
}
app.get('/admin', authorize('admin', 'read'), (req, res) => {
res.send('Admin Content');
});
app.get('/user', authorize('user', 'read'), (req, res) => {
res.send('User Content');
});
Series Index
💖 💪 🙅 🚩
Sachin Gadekar
Posted on August 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.