0% found this document useful (0 votes)
13 views11 pages

Unit-3 Awd

Uploaded by

sen.ankita555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Unit-3 Awd

Uploaded by

sen.ankita555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Understanding Authentication

What is Authentication?

Authentication is the process of verifying the identity of a user. It’s like a digital handshake where the
user proves their identity by providing credentials, typically a username and password.

Common Authentication Methods in Node.js

1. Basic Authentication:

 The simplest form of authentication.

 Users send their credentials (username and password) with each request.

 Implemented via HTTP headers, this method is straightforward but not the most secure.

2. Token-based Authentication:

 Users authenticate with their credentials, and the server responds with a token.

 Subsequent requests include this token for access, reducing the need to resend credentials.

 Commonly implemented with JWT (JSON Web Tokens).

3. OAuth (Open Authorization):

 A protocol that allows third-party services to exchange information without exposing passwords.

 Widely used by platforms like Google, Facebook, and Twitter for login.

4. Session-based Authentication:

 Upon successful login, the server creates a session for the user and stores it on the server.

 The session ID is sent to the client, usually stored as a cookie.

 Subsequent requests use this session ID to validate the user’s identity.


Implementing Authentication in Node.js

To illustrate how to implement authentication, we will use JWT, a popular method due to its stateless
nature and ease of use.

Step 1: Setup Node.js Project

First, create a new Node.js project:

mkdir auth-demo
cd auth-demo
npm init -y

Step 2: Install Required Packages

Install necessary packages such as express for creating the server, jsonwebtoken for handling JWTs,
and bcryptjs for hashing passwords.

npm install express jsonwebtoken bcryptjs body-parser

Step 3: Create Authentication Middleware

Create a simple express server and middleware to handle user authentication.

const express = require('express');


const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');

const app = express();


app.use(bodyParser.json());

const users = []; // In-memory user storage for demo purposes.

app.post('/register', async (req, res) => {


const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
users.push({ username, password: hashedPassword });
res.status(201).send({ message: 'User registered successfully!' });
});

app.post('/login', async (req, res) => {


const { username, password } = req.body;
const user = users.find(user => user.username === username);
if (!user) return res.status(400).send({ message: 'User not found' });

const isPasswordValid = await bcrypt.compare(password, user.password);


if (!isPasswordValid) return res.status(401).send({ message: 'Invalid password' });
const token = jwt.sign({ id: user.username }, 'secret-key', { expiresIn: '1h' });
res.status(200).send({ token });
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Step 4: Protecting Routes

Use middleware to protect routes that require authentication:

const authMiddleware = (req, res, next) => {


const token = req.headers['authorization'];
if (!token) return res.status(401).send({ message: 'No token provided' });

jwt.verify(token, 'secret-key', (err, decoded) => {


if (err) return res.status(500).send({ message: 'Failed to authenticate token' });
req.userId = decoded.id;
next();
});
};

app.get('/protected', authMiddleware, (req, res) => {


res.status(200).send({ message: 'You have access to this protected route!' });
});

Understanding Authorization

What is Authorization?

Authorization is the process of determining what actions a user can perform or what resources they can
access. It’s a set of rules that dictate the permissions of authenticated users.

Authorization Strategies in Node.js

1. Role-based Access Control (RBAC):

 Users are assigned roles, and permissions are granted based on these roles.

 Simplifies permission management, especially in systems with well-defined roles like admin,
user, and guest.

2. Attribute-based Access Control (ABAC):

 Uses attributes (user, resource, environment) to make access decisions.

 More flexible than RBAC but also more complex to implement.

3. Access Control Lists (ACLs):


 Permissions are specified for each user-resource pair.

 Provides granular control but can become unwieldy in large systems.

Implementing Authorization in Node.js

Continuing from our previous example, we can extend the authMiddleware to check user roles:

const roles = {
admin: ['read', 'write', 'delete'],
user: ['read']
};

const roleMiddleware = (requiredRole) => {


return (req, res, next) => {
const userRole = getUserRole(req.userId); // Implement this function to retrieve user role.
if (roles[userRole].includes(requiredRole)) {
next();
} else {
res.status(403).send({ message: 'Forbidden: You do not have access to this resource' });
}
};
};

app.get('/admin', authMiddleware, roleMiddleware('write'), (req, res) => {


res.status(200).send({ message: 'Welcome Admin!' });
});

What is the Bearer Token

A Bearer token is an access token used in OAuth 2.0 and JWT to secure API requests. You include it in
the Authorization header as:

Authorization: Bearer <token>

Here, <token> is an encoded credential string that grants access to resources. The term "Bearer" means
that whoever holds the token can use it—no extra identity proof is needed as long as the token is valid.

How It Works

1. After logging in, the authentication server issues the token.

2. The token contains key details like user ID, expiration time, and a signature for verification.

3. The client sends this token with API requests to access protected endpoints.

4. The server verifies the token before granting access, ensuring secure
and stateless communication.
Introduction to Web Security

Web security is crucial for protecting user data and maintaining trust in your applications. When
developing web applications that handle user information, you need to understand how to properly
implement authentication (verifying who users are) and authorization (determining what they can
access). This guide will help you implement these concepts in your projects, including a blog application
with user authentication.

Why Security Matters

Every website faces security risks. Studies show that during 2020-2021, websites had an average of 15
vulnerabilities, with two of these being high severity. Understanding security fundamentals will help you
build safer applications and protect your users' data.

Password Hashing: Keeping User Credentials Safe

What is Password Hashing?

Password hashing transforms a user's password into a jumbled, unrecognizable string of characters. This
hash is what gets stored in your database instead of the actual password. Think of it like turning a secret
ingredient in a recipe into a code that only makes sense if you have the original ingredient to compare it
with4.

How Password Hashing Works

When a user registers on your website:

1. They create a password

2. Your system runs this password through a hashing algorithm

3. The resulting hash is stored in your database

4. The original password is never saved

When the user logs in later:

1. They enter their password

2. Your system hashes that input using the same algorithm

3. The system compares the new hash with the stored hash

4. If they match, the user gains access

Why Hashing is Better Than Encryption

Passwords should be hashed, not encrypted. The key difference is that hashing is a one-way process-you
can't convert a hash back to the original password. Encryption, on the other hand, is designed to be
reversible if you have the right key1.

Best Practices for Password Hashing

1. Use modern hashing algorithms:


 Argon2id is recommended with minimum 19 MiB memory, iteration count of 2, and 1
degree of parallelism

 If unavailable, use scrypt with minimum cost parameter of 2^17

 For legacy systems, bcrypt with a work factor of 10 or more is acceptable1

2. Always use salting: A salt is a random string added to each password before hashing. Modern
algorithms like bcrypt automatically add salts, making each hash unique even if users have
identical passwords.

3. Consider using peppering: A pepper is a secret value added to passwords before hashing that
isn't stored in your database. Unlike salts (which are unique per user), peppers are shared across
passwords and stored separately in a secure location.

4. Use appropriate work factors: Work factors make hash calculations more computationally
expensive, slowing down potential attackers. A good rule is that calculating a hash should take
less than one second.

Implementing Password Hashing with bcrypt

Here's a simple implementation using Node.js and bcrypt:

javascript

// Step 1: Include the bcrypt module

const bcrypt = require('bcrypt');

// Step 2: Set the salt rounds (complexity)

const saltRounds = 10;

// For registering a new user

async function hashPassword(plainPassword) {

// bcrypt handles the salting automatically

const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);

return hashedPassword;

// Store hashedPassword in your database

// For verifying a login attempt


async function verifyPassword(plainPassword, storedHash) {

const isMatch = await bcrypt.compare(plainPassword, storedHash);

return isMatch; // true if passwords match, false otherwise

This code shows how to hash a password during registration and verify it during login using bcrypt with a
work factor of 102.

What is RBAC(Role-Based Access Control)?

Role-Based Access Control (RBAC) is a method of managing what users can do in your application based
on their assigned roles. Instead of giving permissions directly to individual users, you create roles (like
"Admin," "Editor," or "Viewer") and assign permissions to these roles5.

Why Use RBAC?

RBAC makes managing permissions much easier, especially as your application grows:

 You assign users to roles instead of managing individual permissions

 When you need to change what a certain type of user can do, you modify the role once instead
of updating many individual users

 It reduces errors in permission assignments

 It makes it easier to audit who has access to what5

How RBAC Works

1. Define roles based on job functions or responsibilities (e.g., Admin, Editor, Reader)

2. Assign permissions to each role (e.g., create posts, edit posts, delete posts)

3. Assign users to roles based on their responsibilities

4. When users try to perform actions, check if their role has the necessary permission5

Example RBAC for a Blog Application

For a blog application, you might have these roles:

 Admin: Can create, read, update, and delete all posts and manage users

 Editor: Can create, read, update, and delete their own posts

 Reader: Can only read posts and leave comments

Authentication vs. Authorization

Understanding the Difference

These terms are often confused but represent different security processes:
 Authentication verifies who someone is-it confirms a user's identity ("Are you who you say you
are?")

 Authorization determines what a verified user can access or do ("What are you allowed to
do?")6

The Security Process Flow

1. Authentication comes first: A user provides credentials (username/password)

2. The system verifies these credentials through hashing comparison

3. Only after authentication comes authorization, where the system checks what the
authenticated user is permitted to do based on their role or permissions6

This sequence is critical-you must verify identity before granting access permissions.

Protecting Against Common Security Vulnerabilities

The Open Web Application Security Project (OWASP) maintains a list of the top 10 most critical web
application security risks. This list helps developers understand the most common vulnerabilities and
how to protect against them7.

Key Vulnerabilities to Watch For

1. Broken Authentication: Implement proper password hashing and secure session management

2. Injection Attacks: Validate and sanitize all user inputs

3. Sensitive Data Exposure: Hash passwords and encrypt sensitive information

4. Broken Access Control: Implement proper authentication and authorization checks

5. Cross-Site Scripting (XSS): Escape user-generated content before displaying it

Building a Secure Blog Application

Setting Up Authentication

For a blog project with authentication, you'll need:

1. User Registration System:

javascript

// Example user registration

async function registerUser(username, password, email) {

// Check if username already exists

const existingUser = await findUserByUsername(username);

if (existingUser) {
return { success: false, message: 'Username already taken' };

// Hash the password

const hashedPassword = await bcrypt.hash(password, 10);

// Store the user in the database

const newUser = await saveUser({

username,

password: hashedPassword,

email,

role: 'reader' // Default role

});

return { success: true, user: newUser };

2. Login System:

javascript

async function loginUser(username, password) {

// Find the user

const user = await findUserByUsername(username);

if (!user) {

return { success: false, message: 'Invalid username or password' };

// Verify password

const passwordMatch = await bcrypt.compare(password, user.password);

if (!passwordMatch) {

return { success: false, message: 'Invalid username or password' };


}

// Create a session or JWT token

const token = createAuthToken(user);

return { success: true, token, user };

Implementing Role-Based Access Control

For your blog application, implement middleware to check permissions:

javascript

function checkPermission(requiredPermission) {

return (req, res, next) => {

// Get user from authenticated session/token

const user = req.user;

// Check if user has required permission based on their role

if (hasPermission(user.role, requiredPermission)) {

next(); // Allow the request to continue

} else {

res.status(403).json({ error: 'Access denied' });

};

// Usage in routes

app.post('/posts', checkPermission('create:post'), createPostController);

app.put('/posts/:id', checkPermission('edit:post'), updatePostController);

Protecting Against Common Attacks

1. Prevent SQL Injection: Use parameterized queries or an ORM instead of building SQL strings
2. Protect Against XSS: Sanitize user input and escape output

3. Implement CSRF Protection: Use anti-CSRF tokens

4. Set Secure Headers: Configure secure headers like Content-Security-Policy

5. Limit Login Attempts: Implement rate limiting to prevent brute force attacks

You might also like