Create API Auth with session
- User
Create API Auth with session
- Assistant
Create API Auth with session
Creating API authentication using sessions involves managing user state on the server side and ensuring that each API request is associated with an authenticated session. This approach is commonly used in web applications where maintaining user state is essential. Below, I'll guide you through setting up session-based authentication for an API using Node.js with the Express framework. We'll use Express-Session for session management and bcrypt for password hashing.
We'll create a simple API with the following endpoints:
POST /login - Authenticate a user and create a session.POST /logout - Destroy the user's session.GET /protected - A protected route that requires authentication.Create a new directory for your project and initialize it with npm.
mkdir session-auth-api
cd session-auth-api
npm init -y
Install the necessary packages:
npm install express express-session body-parser bcrypt connect-sqlite3 sqlite3
express - Web framework.express-session - Session middleware.body-parser - Parse incoming request bodies.bcrypt - Password hashing.connect-sqlite3 & sqlite3 - Session store.Create an index.js file and set up the Express server with session management.
// index.js
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const SQLiteStore = require('connect-sqlite3')(session);
const bcrypt = require('bcrypt');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// Session Middleware
app.use(session({
store: new SQLiteStore({
db: 'sessions.sqlite',
dirname: './db',
}),
secret: 'your-secret-key', // Replace with a strong secret in production
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false, // Set to true if using HTTPS
maxAge: 1000 * 60 * 60, // 1 hour
},
}));
// Initialize SQLite Database for Users
const dbPath = path.resolve(__dirname, 'db', 'users.sqlite');
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error('Could not connect to database', err);
} else {
console.log('Connected to SQLite database');
}
});
// Create Users Table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT
)`);
// Helper function to create a new user (for testing)
const createUser = (username, password) => {
const saltRounds = 10;
bcrypt.hash(password, saltRounds, (err, hash) => {
if (err) {
console.error('Error hashing password', err);
return;
}
db.run(`INSERT INTO users (username, password) VALUES (?, ?)`, [username, hash], (err) => {
if (err) {
console.error('Error creating user', err);
} else {
console.log(`User ${username} created.`);
}
});
});
};
// Uncomment the line below to create a test user
// createUser('testuser', 'password123');
For simplicity, we'll interact directly with SQLite. In a production environment, consider using an ORM like Sequelize or TypeORM.
Add routes for login, logout, and a protected route.
// Login Route
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: 'Username and password are required.' });
}
// Fetch user from the database
db.get(`SELECT * FROM users WHERE username = ?`, [username], (err, user) => {
if (err) {
console.error('Database error:', err);
return res.status(500).json({ message: 'Internal server error.' });
}
if (!user) {
return res.status(401).json({ message: 'Invalid credentials.' });
}
// Compare password
bcrypt.compare(password, user.password, (err, result) => {
if (result) {
// Passwords match, create session
req.session.userId = user.id;
return res.json({ message: 'Login successful.' });
} else {
return res.status(401).json({ message: 'Invalid credentials.' });
}
});
});
});
// Logout Route
app.post('/logout', (req, res) => {
if (req.session.userId) {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ message: 'Could not log out.' });
} else {
res.clearCookie('connect.sid');
return res.json({ message: 'Logout successful.' });
}
});
} else {
return res.status(400).json({ message: 'Not logged in.' });
}
});
// Middleware to Protect Routes
const isAuthenticated = (req, res, next) => {
if (req.session.userId) {
next();
} else {
res.status(401).json({ message: 'Unauthorized. Please log in.' });
}
};
// Protected Route
app.get('/protected', isAuthenticated, (req, res) => {
res.json({ message: `Hello User ${req.session.userId}, you have accessed a protected route!` });
});
// Start Server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
The isAuthenticated middleware checks if the userId exists in the session. If it does, the request proceeds; otherwise, it returns a 401 Unauthorized response. You can use this middleware to protect any routes that require authentication.
Start the Server
node index.js
Create a Test User
Uncomment the createUser line in index.js, restart the server once to create the user, then comment it out again to prevent duplicate entries.
Login
Send a POST request to http://localhost:3000/login with JSON body:
{
"username": "testuser",
"password": "password123"
}
On success, the server sets a session cookie.
Access Protected Route
With the session cookie, send a GET request to http://localhost:3000/protected. You should receive a success message.
Logout
Send a POST request to http://localhost:3000/logout to destroy the session.
Use HTTPS: Always use HTTPS to encrypt data in transit, especially when dealing with authentication.
Secure Cookies: Set the secure flag to true in the session cookie when using HTTPS to prevent cookies from being sent over unsecured connections.
cookie: {
httpOnly: true,
secure: true, // Set to true in production
maxAge: 1000 * 60 * 60,
},
Strong Session Secret: Use a strong, unpredictable secret for signing the session ID cookie.
secret: process.env.SESSION_SECRET || 'your-very-secure-secret-key',
Preferably, store it in environment variables.
Session Store: Using a persistent session store like connect-sqlite3 ensures that sessions survive server restarts. For scalable applications, consider using Redis or another robust store.
Prevent Session Fixation: Regenerate session IDs after successful login to prevent session fixation attacks.
// After successful login
req.session.regenerate((err) => {
if (err) {
return res.status(500).json({ message: 'Internal server error.' });
}
req.session.userId = user.id;
res.json({ message: 'Login successful.' });
});
Limit Session Lifespan: Set appropriate maxAge for session cookies and implement mechanisms to refresh or invalidate sessions as needed.
Input Validation: Always validate and sanitize user input to prevent SQL injection and other attacks. Consider using libraries like express-validator.
Session-based authentication is a robust method for managing user state in web applications and APIs. By leveraging Express.js and Express-Session, you can implement secure and scalable authentication mechanisms. Always adhere to security best practices to protect user data and maintain the integrity of your application.
Feel free to expand upon this basic setup by integrating features like role-based access control, account lockout mechanisms after multiple failed login attempts, and using environment variables for configuration management.
Not yet included in a published release.