Next.js course ยท Module 7: Authentication and Authorization
Application security and OWASP
In this lesson5
In previous modules, we focused on implementing authentication, session management, the role and permission system, route protection middleware, and the Context Provider for authentication. Now we will shift our attention to the broader area of web application security, with particular focus on OWASP (Open Web Application Security Project) guidelines.
OWASP is a non-profit organization that works to improve software security. It regularly publishes the Top 10 list of the most serious security threats for web applications, which is a fundamental reference point for developers striving to create secure applications.
OWASP Top 10 and its application in Next.js apps
We will look at how to secure Next.js applications against the most serious threats from the OWASP Top 10 list:
1. Broken Access Control
Threat: Improper implementation of access control, allowing unauthorized users to access protected resources or perform unauthorized operations.
Protection in Next.js:
// 1. Middleware to protect routes
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
// Check user permissions
if (!token) {
return NextResponse.redirect(new URL('/auth/login', request.url));
}
// Role-based access control
if (request.nextUrl.pathname.startsWith('/admin') && token.role !== 'admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
}
// 2. Permission verification in Route Handlers
// app/api/protected/resource/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Checking permissions for a specific resource
const hasPermission = await checkResourcePermission(session.user.id, 'resource-id');
if (!hasPermission) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Continue with resource access...
}
// Function that checks permissions to a resource
async function checkResourcePermission(userId: string, resourceId: string) {
// Implementing the permission check, e.g. via a database query
// It's worth implementing a caching mechanism for frequently checked permissions
return true; // Sample implementation
}Additional best practices:
- Implement access control at the server level, never rely solely on client-side security
- Apply the default deny principle (deny by default)
- Regularly review and test access control mechanisms
- Implement an account lockout mechanism after multiple failed login attempts
2. Cryptographic Failures
Threat: Improper or insufficient application of cryptography, leading to the disclosure of sensitive data.
Protection in Next.js:
// 1. Secure password storage
// lib/auth.ts
import { hash, compare } from 'bcrypt';
// Hashing password during registration
export async function hashPassword(password: string): Promise<string> {
// We use 12 rounds for a good compromise between security and performance
return hash(password, 12);
}
// Verifying password during login
export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
return compare(password, hashedPassword);
}
// 2. Encrypting sensitive data in the database
// lib/encryption.ts
import crypto from 'crypto';
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY as string; // Must be 32 bytes (256 bits)
const IV_LENGTH = 16; // For AES, initialization vector is 16 bytes
export function encrypt(text: string): string {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return `${iv.toString('hex')}:${encrypted}`;
}
export function decrypt(text: string): string {
const [ivHex, encryptedHex] = text.split(':');
const iv = Buffer.from(ivHex, 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}Additional best practices:
- Always use HTTPS for all application pages
- Implement appropriate security-related HTTP headers (HSTS, CSP)
- Regularly update cryptographic libraries
- Implement a cryptographic key rotation strategy
- Do not store sensitive data in local browser storages (localStorage, sessionStorage)
3. Injection
Threat: Injection of untrusted data into interpreters as part of a command or query, which can lead to execution of unauthorized commands or data access.
Protection in Next.js:
// 1. Secure database queries (using an ORM)
// app/api/users/route.ts
import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const name = searchParams.get('name');
// Secure query using an ORM (Prisma)
// Instead of direct injection of parameters into an SQL query
const users = await prisma.user.findMany({
where: {
name: {
contains: name || '',
},
},
select: {
id: true,
name: true,
email: true,
},
});
return NextResponse.json(users);
}
// 2. Input data validation using the zod library
// app/api/products/route.ts
import { NextResponse } from 'next/server';
import { z } from 'zod';
// Validation schema
const ProductSchema = z.object({
name: z.string().min(1).max(100),
price: z.number().positive(),
description: z.string().optional(),
categoryId: z.string().uuid(),
});
export async function POST(request: Request) {
try {
const body = await request.json();
// Validate input data
const result = ProductSchema.safeParse(body);
if (!result.success) {
return NextResponse.json(
{ error: 'Invalid input', details: result.error.format() },
{ status: 400 }
);
}
// Further processing of safe, validated data...
} catch (error) {
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}Additional best practices:
- Filter and sanitize input and output data
- Use complex, randomized passwords and session identifiers
- Implement session timeout and limit login attempts
- Escape all data before placing it in SQL commands, scripts, or HTML
- Avoid dynamic generation of JavaScript code by string concatenation
4. Insecure Design
Threat: Lack of appropriate security mechanisms at the application design level, leading to fundamental security vulnerabilities.
Protection in Next.js:
// 1. Password security policy implementation
// lib/passwordPolicy.ts
export function isPasswordStrong(password: string): { isValid: boolean; reason?: string } {
// Minimum length of 8 characters
if (password.length < 8) {
return { isValid: false, reason: 'Password must be at least 8 characters' };
}
// Requires uppercase letters
if (!/[A-Z]/.test(password)) {
return { isValid: false, reason: 'Password must contain at least one uppercase letter' };
}
// Requires lowercase letters
if (!/[a-z]/.test(password)) {
return { isValid: false, reason: 'Password must contain at least one lowercase letter' };
}
// Requires digits
if (!/[0-9]/.test(password)) {
return { isValid: false, reason: 'Password must contain at least one digit' };
}
// Requires special characters
if (!/[^A-Za-z0-9]/.test(password)) {
return { isValid: false, reason: 'Password must contain at least one special character' };
}
// Check if the password is not on the list of common, easily guessable passwords
const commonPasswords = ['Password123!', 'Admin123!', '12345678Aa!', 'Qwerty123!']; // In practice, this should be a larger database
if (commonPasswords.includes(password)) {
return { isValid: false, reason: 'Password is too common and easy to guess' };
}
return { isValid: true };
}
// 2. Implementing a permission system based on the data model
// lib/permissions.ts
import { prisma } from '@/lib/prisma';
// Model allowing certain operations only to the resource owner
export async function canModifyResource(userId: string, resourceId: string): Promise<boolean> {
const resource = await prisma.resource.findUnique({
where: { id: resourceId },
select: { userId: true },
});
// Resource does not exist or the user is not the owner
if (!resource || resource.userId !== userId) {
return false;
}
return true;
}Additional best practices:
- Implement a multi-layered protection mechanism (defense in depth)
- Perform threat modeling at an early stage of application development
- Design with the principle of least privilege in mind
- Treat user data as untrusted and always validate it
- Regularly review and update security mechanisms
5. Security Misconfiguration
Threat: Improper security configuration in any application component, which can lead to unauthorized access or data leakage.
Protection in Next.js:
// 1. Content Security Policy configuration
// next.config.js
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://cdn.example.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
font-src 'self' https://fonts.gstatic.com;
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-src 'self';
`;
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim(),
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=(self)',
},
],
},
];
},
};
// 2. Secure use of environment variables
// lib/config.ts
interface Config {
database: {
url: string;
};
auth: {
secret: string;
tokenExpiration: number;
};
services: {
apiKey: string;
endpoint: string;
};
}
export const config: Config = {
database: {
url: process.env.DATABASE_URL || '',
},
auth: {
secret: process.env.AUTH_SECRET || '',
tokenExpiration: Number(process.env.TOKEN_EXPIRATION) || 3600,
},
services: {
apiKey: process.env.SERVICE_API_KEY || '',
endpoint: process.env.SERVICE_ENDPOINT || '',
},
};
// Function to verify the configuration on application startup
export function validateConfig() {
const requiredEnvVars = [
'DATABASE_URL',
'AUTH_SECRET',
'SERVICE_API_KEY',
'SERVICE_ENDPOINT',
];
const missingEnvVars = requiredEnvVars.filter(
(envVar) => !process.env[envVar]
);
if (missingEnvVars.length > 0) {
throw new Error(`Missing required environment variables: ${missingEnvVars.join(', ')}`);
}
if (process.env.AUTH_SECRET && process.env.AUTH_SECRET.length < 32) {
throw new Error('AUTH_SECRET should be at least 32 characters long for security');
}
console.log('Configuration validated successfully');
}Additional best practices:
- Remove or disable unnecessary features, components, and dependencies
- Regularly update all application components and dependencies
- Implement a configuration auditing mechanism
- Never place sensitive data in source code or publicly accessible files
- Use different configurations for development and production environments
6. Vulnerable and Outdated Components
Threat: Using components and libraries containing known security vulnerabilities or that are no longer supported.
Protection in Next.js:
// 1. Automatic dependency scanning
// package.json
{
"scripts": {
"audit": "npm audit",
"audit:fix": "npm audit fix",
"outdated": "npm outdated",
"update": "npm update",
"deps:check": "npx depcheck",
"prepare": "husky install"
},
"husky": {
"hooks": {
"pre-commit": "npm run audit"
}
}
}
// 2. Introducing an SRI (Subresource Integrity) policy
// For critical external JavaScript libraries
// app/layout.tsx (example)
import Script from 'next/script';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{/* Using SRI to verify the integrity of an external script */}
<Script
src="https://cdn.example.com/library.min.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossOrigin="anonymous"
/>
</head>
<body>{children}</body>
</html>
);
}Additional best practices:
- Regularly running
npm auditor using tools like Snyk, Dependabot - Removing unused dependencies
- Subscribing to notifications about security vulnerabilities in used libraries
- Using trusted, well-maintained libraries with an active community
- Preparing procedures for quick component updates after vulnerability discovery
7. Identification and Authentication Failures
Threat: Improper implementation of authentication mechanisms, allowing attackers to access user accounts.
Protection in Next.js:
// 1. Login attempt limiting implementation
// lib/rateLimit.ts
import { Redis } from '@upstash/redis';
const redis = new Redis({
url: process.env.UPSTASH_REDIS_URL!,
token: process.env.UPSTASH_REDIS_TOKEN!,
});
export async function rateLimit(
identifier: string, // IP or user identifier
limit: number, // Maximum number of attempts
window: number // Time window in seconds
): Promise<{ success: boolean; remaining: number; reset: number }> {
const now = Math.floor(Date.now() / 1000);
const key = `ratelimit:${identifier}`;
// Fetch the current rate-limit data
const entry = await redis.hgetall(key);
if (!entry.count) {
// First entry
await redis.hset(key, {
count: 1,
reset: now + window,
});
await redis.expire(key, window);
return {
success: true,
remaining: limit - 1,
reset: now + window,
};
}
// Check if the time window has passed
if (parseInt(entry.reset) < now) {
// Reset the counter
await redis.hset(key, {
count: 1,
reset: now + window,
});
await redis.expire(key, window);
return {
success: true,
remaining: limit - 1,
reset: now + window,
};
}
// Check if the limit has been exceeded
const count = parseInt(entry.count);
if (count >= limit) {
return {
success: false,
remaining: 0,
reset: parseInt(entry.reset),
};
}
// Update the counter
await redis.hincrby(key, 'count', 1);
return {
success: true,
remaining: limit - count - 1,
reset: parseInt(entry.reset),
};
}
// 2. Login page implementation with attempt limiting
// app/api/auth/login/route.ts
import { NextResponse } from 'next/server';
import { rateLimit } from '@/lib/rateLimit';
export async function POST(request: Request) {
try {
const { email, password } = await request.json();
// Get the user IP address
const ip = request.headers.get('x-forwarded-for') || 'unknown';
// Limit login attempts: 5 attempts within 15 minutes
const rateLimitResult = await rateLimit(ip, 5, 15 * 60);
if (!rateLimitResult.success) {
return NextResponse.json(
{
error: 'Too many login attempts. Please try again later.',
reset: rateLimitResult.reset,
},
{ status: 429 }
);
}
// Continue the login process...
} catch (error) {
console.error('Login error:', error);
return NextResponse.json(
{ error: 'An error occurred during login' },
{ status: 500 }
);
}
}Additional best practices:
- Implement strong password requirements
- Require multi-factor authentication (MFA) for administrator accounts and users with high permissions
- Do not reveal detailed information about authentication errors
- Implement secure password recovery mechanisms
- Use one-time token mechanisms for critical operations
8. Software and Data Integrity Failures
Threat: Lack of software and data integrity verification, allowing the introduction of incorrect or malicious components.
Protection in Next.js:
// 1. Implementation of a digital signature mechanism for critical data
// lib/signatures.ts
import crypto from 'crypto';
const SIGNATURE_KEY = process.env.SIGNATURE_KEY!;
// Generating the signature for the data
export function signData(data: any): string {
const dataString = typeof data === 'string' ? data : JSON.stringify(data);
return crypto
.createHmac('sha256', SIGNATURE_KEY)
.update(dataString)
.digest('hex');
}
// Verifying the data signature
export function verifySignature(data: any, signature: string): boolean {
const expectedSignature = signData(data);
return crypto.timingSafeEqual(
Buffer.from(expectedSignature, 'hex'),
Buffer.from(signature, 'hex')
);
}
// 2. Implementation of webhook verification for external services
// app/api/webhooks/payment-processor/route.ts
import { NextResponse } from 'next/server';
import { verifySignature } from '@/lib/signatures';
export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get('X-Webhook-Signature') || '';
// Verifying the webhook signature
if (!verifySignature(body, signature)) {
console.error('Invalid webhook signature');
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 401 }
);
}
// Processing the verified webhook...
const data = JSON.parse(body);
//
return NextResponse.json({ status: 'success' });
}Additional best practices:
- Verify the integrity of files and source code in the CI/CD process
- Verify the origin of external libraries and components
- Use SRI (Subresource Integrity) mechanisms for external resources
- Implement automated security tests in the CI/CD process
- Monitor and analyze changes in configuration files and application code
9. Security Logging and Monitoring Failures
Threat: Insufficient logging, monitoring, and alerting of security events, which prevents detection, escalation, and response to incidents.
Protection in Next.js:
// 1. Implementing extensive logging
// lib/logger.ts
import winston from 'winston';
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
defaultMeta: { service: 'next-app' },
transports: [
// Local log saving at error level
new winston.transports.File({ filename: 'error.log', level: 'error' }),
// Local saving of all logs
new winston.transports.File({ filename: 'combined.log' }),
],
});
// In production, send logs to a monitoring service
if (process.env.NODE_ENV === 'production') {
// Example for Datadog
// Requires installing '@datadog/winston'
// import { datadog } from '@datadog/winston';
// logger.add(new datadog({
// apiKey: process.env.DATADOG_API_KEY,
// hostname: process.env.HOSTNAME,
// service: 'next-app',
// ddsource: 'nodejs',
// }));
}
// Functions for logging security events
export function logSecurityEvent(
eventType: string,
data: any,
severity: 'info' | 'warn' | 'error' = 'info'
) {
logger.log({
level: severity,
message: `Security event: ${eventType}`,
eventType,
data,
timestamp: new Date().toISOString(),
});
}
export function logAuthEvent(
userId: string | null,
action: 'login' | 'logout' | 'failed_login' | 'password_reset' | 'account_locked',
details: any = {}
) {
logSecurityEvent(
`auth_${action}`,
{
userId,
ip: details.ip,
userAgent: details.userAgent,
...details,
},
action === 'failed_login' || action === 'account_locked' ? 'warn' : 'info'
);
}
// 2. Implementing middleware for logging HTTP requests
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { logSecurityEvent } from '@/lib/logger';
export function middleware(request: NextRequest) {
// Save basic request information
const requestInfo = {
method: request.method,
path: request.nextUrl.pathname,
ip: request.ip || 'unknown',
userAgent: request.headers.get('user-agent') || 'unknown',
referer: request.headers.get('referer') || 'unknown',
};
// Log only relevant paths (skip static assets, etc.)
if (!request.nextUrl.pathname.match(/\.(ico|png|jpg|jpeg|svg|css|js)$/)) {
logSecurityEvent('http_request', requestInfo);
}
// Potential attack detection
if (detectPotentialAttack(request)) {
logSecurityEvent('potential_attack', requestInfo, 'warn');
}
return NextResponse.next();
}
// Function that detects potential attacks based on request patterns
function detectPotentialAttack(request: NextRequest): boolean {
const url = request.nextUrl.toString().toLowerCase();
const body = request.body; // May be unavailable in middleware
// Detection of basic attack attempts
const attackPatterns = [
/(\.\.\/|\.\.\\/)/i, // Path traversal
/('|")(;|--|\+|\%|\#|\)/i, // Basic SQL injection
/<script>[^<]*<\/script>/i, // Basic XSS
/etc\/passwd/i, // Path disclosure
/\/(wp-admin|wp-content|wp-includes)/i, // WordPress scanning
];
return attackPatterns.some(pattern => pattern.test(url));
}Additional best practices:
- Implement a centralized logging and monitoring system
- Configure automatic alerting for suspicious events
- Provide mechanisms for correlating events from different parts of the application
- Regularly analyze logs for unauthorized activities
- Store logs for an appropriately long time in accordance with regulations and business needs
10. Server-Side Request Forgery
Threat: SSRF attacks allow an attacker to invoke HTTP requests from the application server to internal or external resources to which the server has access.
Protection in Next.js:
// 1. Secure URL fetching implementation
// lib/safeFetch.ts
import { URL } from 'url';
import fetch from 'node-fetch';
// List of allowed domains
const ALLOWED_HOSTS = [
'api.example.com',
'api.trusted-service.com',
'cdn.example.com',
];
// List of forbidden IP addresses (private IP ranges)
const BLOCKED_IP_RANGES = [
// Local
/^127\.\d+\.\d+\.\d+$/, // 127.0.0.0/8
/^10\.\d+\.\d+\.\d+$/, // 10.0.0.0/8
/^172\.(1[6-9]|2\d|3[0-1])\.\d+\.\d+$/, // 172.16.0.0/12
/^192\.168\.\d+\.\d+$/, // 192.168.0.0/16
// Link-local
/^169\.254\.\d+\.\d+$/, // 169.254.0.0/16
// Multicast
/^2(2[4-9]|3\d)\.\d+\.\d+\.\d+$/, // 224.0.0.0/4
];
export async function safeFetch(urlString: string, options: RequestInit = {}) {
try {
// Parse URL to check its components
const url = new URL(urlString);
// Check if the domain is on the allowed list
if (!ALLOWED_HOSTS.includes(url.hostname)) {
throw new Error(`Host not allowed: ${url.hostname}`);
}
// Check if the IP address is not on the blocked list
// This requires additional logic for DNS resolution
// Simplified version of checking directly by host
if (BLOCKED_IP_RANGES.some(pattern => pattern.test(url.hostname))) {
throw new Error(`IP address not allowed: ${url.hostname}`);
}
// Check if the protocol is secure
if (url.protocol !== 'https:') {
throw new Error(`Protocol not allowed: ${url.protocol}`);
}
// Perform the HTTP request after URL verification
return fetch(url.toString(), options);
} catch (error) {
console.error('Safe fetch error:', error);
throw new Error(`Invalid or disallowed URL: ${urlString}`);
}
}
// 2. API proxy implementation with URL validation
// app/api/proxy/route.ts
import { NextResponse } from 'next/server';
import { safeFetch } from '@/lib/safeFetch';
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const targetUrl = searchParams.get('url');
if (!targetUrl) {
return NextResponse.json(
{ error: 'URL parameter is required' },
{ status: 400 }
);
}
try {
// Use the secure fetch function
const response = await safeFetch(targetUrl);
const data = await response.text();
return new NextResponse(data, {
status: response.status,
headers: {
'Content-Type': response.headers.get('Content-Type') || 'text/plain',
},
});
} catch (error) {
return NextResponse.json(
{ error: 'Invalid or disallowed URL' },
{ status: 400 }
);
}
} catch (error) {
console.error('Proxy error:', error);
return NextResponse.json(
{ error: 'Server error' },
{ status: 500 }
);
}
}Additional best practices:
- Implement allow-lists of domains instead of block-lists
- Use a network firewall to block connections to internal resources
- Filter and sanitize input data containing URLs
- Use minimal permissions for service and application accounts
- Avoid passing full responses from external APIs to the client
Implementing Security Headers in Next.js
Security headers are a key element in protecting web applications. Next.js allows easy configuration of these headers in the file next.config.js:
// next.config.js
const securityHeaders = [
{
key: 'X-DNS-Prefetch-Control',
value: 'on',
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=(self), interest-cohort=()',
},
];
module.exports = {
async headers() {
return [
{
// Apply these headers to all paths
source: '/(.*)',
headers: securityHeaders,
},
];
},
// Other Next.js configurations...
};Penetration testing and security testing automation
Tests are a key element in ensuring application security. Below is an example of integrating security tests with the CI/CD process:
# .github/workflows/security.yml
name: Security Checks
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
schedule:
- cron: '0 0 * * 0' # Weekly scan
jobs:
security-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run npm audit
run: npm audit --audit-level=high
- name: OWASP ZAP Scan
uses: zaproxy/action-baseline@v0.6.1
with:
target: 'https://staging.example.com' # Your staging environment URL
- name: Run Snyk to check for vulnerabilities
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
- name: Check for secrets in code
uses: gitleaks/gitleaks-action@v1.6.0Security checklist for Next.js applications
Below is a checklist you can use to assess the security of your Next.js application:
General security
- Appropriate security-related HTTP headers have been implemented
- HTTPS is used for all environments
- Input data validation mechanism has been implemented
- Inactive sessions are automatically logged out
- Sensitive information is not stored in publicly accessible files
- Logs do not contain sensitive data
Authentication and authorization
- Passwords are properly hashed and salted
- Login attempt limiting mechanism has been implemented
- Password security policy has been implemented
- Role and permission system works correctly
- Sessions are securely managed
- Multi-factor authentication (MFA) has been implemented for administrator accounts
Data processing
- Data is properly sanitized before rendering
- Database queries are parameterized (protected against SQL Injection)
- XSS prevention mechanisms have been implemented
- API endpoints are protected against unauthorized access
- CSRF token implementation prevents CSRF attacks
Dependencies and code
- All dependencies are up to date and free of known vulnerabilities
- Code is regularly scanned for security vulnerabilities
- Best coding practices are applied
- There are no hardcoded secrets and keys in the code
Monitoring and incident response
- Security event logging mechanism has been implemented
- Security incident response procedures have been defined
- Regular penetration tests are conducted
- Monitoring and alerting mechanisms have been implemented
Summary
Web application security, including Next.js applications, requires a comprehensive approach and constant attention. In this module, we covered the most important threats defined in the OWASP Top 10 and how to minimize them in the context of Next.js applications.
Key points to remember:
- Comprehensive approach - security should be considered at every stage of application development
- Principle of least permissions - grant minimum permissions necessary to perform the task
- Validation and sanitization - always validate and sanitize input data
- Updates and patches - regularly update dependencies and apply security patches
- Monitoring and logging - implement extensive monitoring and logging mechanisms
- Testing - regularly perform security tests
Remember that security is a process, not a product. It requires constant improvement and adaptation to new threats.
In the next module, we will look at security auditing and monitoring to better understand how to detect and respond to potential security incidents.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Demo: OWASP Top 10
interface Vulnerability {
id: string;
name: string;
owaspId: string;
severity: 'critical' | 'high' | 'medium';
description: string;
example: string;
prevention: string[];
}
const owaspTop10: Vulnerability[] = [
{ id: '1', name: 'Broken Access Control', owaspId: 'A01:2021', severity: 'critical',
description: 'Lack of access control - users act outside their permissions.',
example: 'GET /api/users/123/data - no identity verification',
prevention: ['Deny access by default', 'Implement RBAC', 'Validate on the server side'] },
{ id: '2', name: 'Cryptographic Failures', owaspId: 'A02:2021', severity: 'critical',
description: 'Weak encryption or no data encryption.',
example: 'Passwords stored in plaintext in the database',
prevention: ['bcrypt/argon2 for passwords', 'HTTPS', 'Do not store unnecessary data'] },
{ id: '3', name: 'Injection', owaspId: 'A03:2021', severity: 'critical',
description: 'SQL, NoSQL, OS command injection.',
example: 'SELECT * FROM users WHERE id = userInput (without parameterization)',
prevention: ['Parameterized queries', 'Data validation', 'Use an ORM'] },
{ id: '4', name: 'Insecure Design', owaspId: 'A04:2021', severity: 'high',
description: 'Lack of security patterns in the architecture.',
example: 'No rate limiting on login',
prevention: ['Threat modeling', 'Security patterns', 'Security code review'] },
{ id: '5', name: 'Security Misconfiguration', owaspId: 'A05:2021', severity: 'high',
description: 'Default settings, open ports, debug enabled in production.',
example: 'Detailed errors exposed in production',
prevention: ['Hardening', 'Least privilege', 'Configuration audits'] },
{ id: '6', name: 'Vulnerable Components', owaspId: 'A06:2021', severity: 'medium',
description: 'Libraries with known vulnerabilities.',
example: 'Outdated lodash version with prototype pollution',
prevention: ['npm audit', 'Update dependencies', 'Monitor CVEs'] },
{ id: '7', name: 'Auth Failures', owaspId: 'A07:2021', severity: 'critical',
description: 'Weak passwords, no MFA, vulnerable tokens.',
example: 'No limit on login attempts',
prevention: ['MFA', 'Strong password policies', 'Rate limiting'] },
{ id: '8', name: 'Data Integrity', owaspId: 'A08:2021', severity: 'high',
description: 'Software and data integrity failures.',
example: 'CI/CD without artifact verification',
prevention: ['Artifact signing', 'Integrity verification', 'Secure CI/CD'] },
];
const sevColors: Record<string, string> = { critical: '#ef4444', high: '#f59e0b', medium: '#3b82f6' };
function OWASPDemo() {
const [selected, setSelected] = useState<Vulnerability | null>(null);
const [checked, setChecked] = useState<Set<string>>(new Set());
const toggle = (id: string) => setChecked(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
const score = Math.round((checked.size / owaspTop10.length) * 100);
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
<h1 style={{ color: '#64ffda', marginBottom: '8px' }}>OWASP Top 10 Checklist</h1>
<div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '24px', padding: '16px', background: '#1a1a2e', borderRadius: '8px', border: '1px solid #333' }}>
<div style={{ width: '60px', height: '60px', borderRadius: '50%', border: '3px solid ' + (score >= 75 ? '#10b981' : score >= 50 ? '#f59e0b' : '#ef4444'), display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '20px', fontWeight: 'bold', color: score >= 75 ? '#10b981' : score >= 50 ? '#f59e0b' : '#ef4444' }}>{score}%</div>
<div><strong>Security Score</strong><div style={{ fontSize: '13px', color: '#8892b0' }}>{checked.size}/{owaspTop10.length} secured</div></div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 1fr' : '1fr', gap: '20px' }}>
<div style={{ display: 'grid', gap: '8px' }}>
{owaspTop10.map(v => (
<div key={v.id} onClick={() => setSelected(v)} style={{
padding: '12px 16px', borderRadius: '8px', cursor: 'pointer',
background: selected?.id === v.id ? '#1a2a3e' : '#1a1a2e',
border: selected?.id === v.id ? '1px solid #64ffda' : '1px solid #333',
display: 'flex', alignItems: 'center', gap: '12px',
}}>
<input type="checkbox" checked={checked.has(v.id)} onChange={() => toggle(v.id)} onClick={e => e.stopPropagation()} />
<span style={{ fontSize: '12px', padding: '2px 8px', borderRadius: '12px', background: sevColors[v.severity] + '30', color: sevColors[v.severity] }}>{v.severity}</span>
<strong style={{ fontSize: '14px' }}>{v.owaspId}: {v.name}</strong>
</div>
))}
</div>
{selected && (
<div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
<h3 style={{ color: '#64ffda', marginTop: 0 }}>{selected.owaspId}: {selected.name}</h3>
<p style={{ color: '#8892b0' }}>{selected.description}</p>
<div style={{ background: '#0f0f23', padding: '12px', borderRadius: '6px', marginBottom: '12px' }}>
<strong style={{ color: '#ef4444', fontSize: '13px' }}>Example:</strong>
<pre style={{ fontSize: '12px', color: '#f59e0b', margin: '8px 0 0', whiteSpace: 'pre-wrap' }}>{selected.example}</pre>
</div>
<strong style={{ color: '#10b981', fontSize: '13px' }}>Prevention:</strong>
<ul style={{ fontSize: '13px', color: '#8892b0', paddingLeft: '20px', margin: '8px 0 0' }}>
{selected.prevention.map((p, i) => <li key={i}>{p}</li>)}
</ul>
</div>
)}
</div>
</div>
);
}
export default OWASPDemo;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Multi-Factor Authentication (MFA) adds:
2. CSRF attacks can be prevented by:
These are 2 of 6 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the import and usage syntax of redirect
- Click in order
Arrange the JWT token structure:
- Vertical ordering
Arrange the elements in the correct order: Track requests โ Check limits โ Block/Al
- Vertical ordering
Arrange the JWT token lifecycle:
Tasks after this lesson
- QuestionMulti-Factor Authentication (MFA) adds:
- QuestionCSRF attacks can be prevented by:
- QuestionSession hijacking can be prevented by:
- Put in orderredirect Syntax from next/navigation
- QuestionWebAuthn/FIDO2 offers:
- Click in orderJWT Token Structure: Header.Payload.Signature
- Put in orderOrder: Track requests โ Check limits โ Block/Allow
- Put in orderJWT Token Lifecycle
- QuestionRate limiting in authentication helps against:
- QuestionOWASP and Application Security