<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ owasp - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ owasp - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:33:48 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/owasp/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Engineering Anatomy of API Vulnerabilities: A Deep Dive into the OWASP API Security Top 10 ]]>
                </title>
                <description>
                    <![CDATA[ Most security articles read like threat reports. They describe vulnerabilities from the outside looking in: what an attacker does, what the impact is, and how many systems are affected globally. That' ]]>
                </description>
                <link>https://www.freecodecamp.org/news/engineering-anatomy-of-api-vulnerabilities-owasp-api-security-top-10/</link>
                <guid isPermaLink="false">6ac381f06fd156dcaf4d765b</guid>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ securityawareness ]]>
                    </category>
                
                    <category>
                        <![CDATA[ OWASP TOP 10 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #OWASP LLM Top 10 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ application sec ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ owasp ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Application Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwaseyi Fatunmole ]]>
                </dc:creator>
                <pubDate>Mon, 05 Oct 2026 10:54:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/58e0ba94-ccc6-4e4e-aa19-9480cb060d23.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most security articles read like threat reports. They describe vulnerabilities from the outside looking in: what an attacker does, what the impact is, and how many systems are affected globally. That's useful context, but it doesn't help engineers build better systems.</p>
<p>This article is different. It looks at each OWASP API Security Top 10 vulnerability from the inside: what engineering decision allowed it to exist, which architectural principle was violated, and what the engineering standard should be to prevent it from ever shipping to production.</p>
<p>I've spent years building production applications at scale in regulated financial environments. The vulnerabilities in this list aren't theoretical. I've seen most of them in real systems. Some of them I caught before they reached production. Some of them were already live when I arrived. Every single one of them was preventable...and not by security tools, but by engineering discipline.</p>
<p>That's the lens this article uses.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-what-is-the-owasp-api-security-top-10">What is the OWASP API Security Top 10?</a></p>
</li>
<li><p><a href="#heading-1-broken-object-level-authorization-bola">1. Broken Object Level Authorization (BOLA)</a></p>
</li>
<li><p><a href="#heading-2-broken-authentication">2. Broken Authentication</a></p>
</li>
<li><p><a href="#heading-3-broken-object-property-level-authorization-bopla">3. Broken Object Property Level Authorization (BOPLA)</a></p>
</li>
<li><p><a href="#heading-4-unrestricted-resource-consumption">4. Unrestricted Resource Consumption</a></p>
</li>
<li><p><a href="#heading-5-broken-function-level-authorization-bfla">5. Broken Function Level Authorization (BFLA)</a></p>
</li>
<li><p><a href="#heading-6-unrestricted-access-to-sensitive-business-flows">6. Unrestricted Access to Sensitive Business Flows</a></p>
</li>
<li><p><a href="#heading-7-security-misconfiguration">7. Security Misconfiguration</a></p>
</li>
<li><p><a href="#heading-8-improper-inventory-management">8. Improper Inventory Management</a></p>
</li>
<li><p><a href="#heading-9-unsafe-consumption-of-apis">9. Unsafe Consumption of APIs</a></p>
</li>
<li><p><a href="#heading-10-server-side-request-forgery-ssrf">10. Server-Side Request Forgery (SSRF)</a></p>
</li>
<li><p><a href="#heading-engineering-vulnerabilities-beyond-the-owasp-list">Engineering Vulnerabilities Beyond the OWASP List</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before reading this article, you should be comfortable with:</p>
<ul>
<li><p>Building APIs in any language or framework</p>
</li>
<li><p>Basic understanding of authentication: what tokens and sessions are</p>
</li>
<li><p>What a database query looks like at a high level</p>
</li>
<li><p>General software architecture concepts, like layers, services, and gateways</p>
</li>
</ul>
<p>You don't need a security background. This article explains every vulnerability from an engineering perspective, not a security analyst perspective.</p>
<h2 id="heading-what-is-the-owasp-api-security-top-10">What is the OWASP API Security Top 10?</h2>
<p>OWASP stands for Open Web Application Security Project. It's a non-profit foundation that produces freely available security guidance for engineers and organizations. The OWASP API Security Top 10 is a regularly updated list of the most critical API vulnerabilities found in production systems globally.</p>
<p>It's not a theoretical list. It's compiled from real security incidents, penetration test findings, and vulnerability reports from production systems across industries. Every item on this list has caused real data breaches, real financial losses, and real regulatory penalties in real organizations.</p>
<p>Understanding this list isn't optional for engineers building APIs. It's foundational knowledge.</p>
<h2 id="heading-1-broken-object-level-authorization-bola">1. Broken Object Level Authorization (BOLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A user is authenticated and they have a valid token. But they can access data that doesn't belong to them simply by changing an identifier in the request.</p>
<pre><code class="language-plaintext">GET /api/accounts/12345/transactions
</code></pre>
<p>User A is authenticated and owns account 12345. They change the account number:</p>
<pre><code class="language-plaintext">GET /api/accounts/99999/transactions
</code></pre>
<p>If the API returns User B's transactions, BOLA exists. The user is authenticated but the API isn't verifying that the authenticated user owns the requested resource.</p>
<p>This is the most common API vulnerability in the world. It consistently tops the OWASP list because it's so easy to introduce and so easy to miss in code review.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>BOLA happens when authorization is treated as a binary question: is this user authenticated? Yes or no. The API checks whether the user has a valid token and stops there. It never asks the second question: does this authenticated user own the specific resource they're requesting?</p>
<p>The authentication isn't ID-agnostic. It proves who you are but it never proves whether the thing you are asking for belongs to you.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Authorization must happen at the service layer, not just at the API gateway. The API gateway can verify that the token is valid. Only the service layer knows whether the authenticated user owns the resource being requested.</p>
<p><strong>Dart (service layer enforcement):</strong></p>
<pre><code class="language-dart">class TransactionService {
  final TransactionRepository _repository;
  final AuthContext _authContext;

  TransactionService(this._repository, this._authContext);

  Future&lt;Result&lt;List&lt;Transaction&gt;, AppException&gt;&gt; getTransactions(
    String accountId,
  ) async {
    final currentUserId = _authContext.currentUserId;

    // fetch the account first
    final account = await _repository.findAccountById(accountId);

    if (account == null) {
      return Result.failure(AppException.notFound('Account not found'));
    }

    // verify ownership before returning any data
    if (account.ownerId != currentUserId) {
      return Result.failure(
        AppException.forbidden('Access denied to this account'),
      );
    }

    final transactions = await _repository.findByAccountId(accountId);
    return Result.success(transactions);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public async Task&lt;Result&lt;IEnumerable&lt;Transaction&gt;&gt;&gt; GetTransactions(
    string accountId,
    ClaimsPrincipal currentUser)
{
    var userId = currentUser.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    var account = await _repository.FindAccountByIdAsync(accountId);

    if (account == null)
        return Result.Failure&lt;IEnumerable&lt;Transaction&gt;&gt;("Account not found");

    // ownership check — never skip this
    if (account.OwnerId != userId)
        return Result.Failure&lt;IEnumerable&lt;Transaction&gt;&gt;("Access denied");

    var transactions = await _repository.FindByAccountIdAsync(accountId);
    return Result.Success(transactions);
}
</code></pre>
<p>The ownership check must happen on every request that accesses a specific resource. Not just on first load or on write operations. Every single request.</p>
<h2 id="heading-2-broken-authentication">2. Broken Authentication</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Weak tokens, no token expiry, no rate limiting on authentication endpoints, or sessions that never terminate on logout. Any weakness in the mechanism that identifies who's making a request.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Authentication is treated as a solved problem once it's working. Engineers implement login, get a token back, and move on. The failure modes (like what happens when a token is stolen, or if an attacker hammers the login endpoint with a list of passwords, or when a user logs out) are never designed for.</p>
<p>The authentication mechanism must be designed for adversarial conditions, not just for happy path usage.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p><strong>Token expiry is mandatory.</strong> Access tokens should be short-lived: 15 minutes to 1 hour. Refresh tokens handle session continuity. Short-lived access tokens limit the damage window when a token is stolen.</p>
<p><strong>Rate limiting on authentication endpoints is mandatory.</strong> A login endpoint without rate limiting is an open invitation for brute force attacks. An attacker with a list of 10 million email and password combinations will systematically try every one.</p>
<p><strong>Sessions must actually terminate on logout.</strong> If you're using stateful sessions, the session must be invalidated server-side on logout. If you're using JWT, maintain a token blocklist or use a very short expiry with refresh token rotation.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class AuthService {
  final TokenRepository _tokenRepository;
  final RateLimiter _rateLimiter;

  AuthService(this._tokenRepository, this._rateLimiter);

  Future&lt;Result&lt;AuthTokens, AppException&gt;&gt; login(
    String email,
    String password,
    String ipAddress,
  ) async {
    // rate limit by IP to prevent brute force
    final isAllowed = await _rateLimiter.checkLimit(
      key: 'login:$ipAddress',
      maxAttempts: 5,
      windowSeconds: 300,
    );

    if (!isAllowed) {
      return Result.failure(
        AppException.rateLimited('Too many login attempts. Try again later.'),
      );
    }

    final user = await _validateCredentials(email, password);

    if (user == null) {
      return Result.failure(
        AppException.unauthorized('Invalid credentials'),
      );
    }

    // short-lived access token
    final accessToken = _generateAccessToken(user, expiryMinutes: 15);

    // longer-lived refresh token, stored server-side
    final refreshToken = _generateRefreshToken(user);
    await _tokenRepository.storeRefreshToken(user.id, refreshToken);

    return Result.success(AuthTokens(
      accessToken: accessToken,
      refreshToken: refreshToken,
    ));
  }

  Future&lt;void&gt; logout(String userId, String refreshToken) async {
    // invalidate the refresh token server-side on logout
    await _tokenRepository.revokeRefreshToken(userId, refreshToken);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public async Task&lt;Result&lt;AuthTokens&gt;&gt; Login(
    LoginRequest request,
    string ipAddress)
{
    var isAllowed = await _rateLimiter.CheckLimit(
        key: $"login:{ipAddress}",
        maxAttempts: 5,
        windowSeconds: 300);

    if (!isAllowed)
        return Result.Failure&lt;AuthTokens&gt;("Too many login attempts.");

    var user = await _userService.ValidateCredentials(
        request.Email,
        request.Password);

    if (user == null)
        return Result.Failure&lt;AuthTokens&gt;("Invalid credentials");

    var accessToken = _tokenService.GenerateAccessToken(user, expiryMinutes: 15);
    var refreshToken = _tokenService.GenerateRefreshToken(user);

    await _tokenRepository.StoreRefreshToken(user.Id, refreshToken);

    return Result.Success(new AuthTokens(accessToken, refreshToken));
}

public async Task Logout(string userId, string refreshToken)
{
    await _tokenRepository.RevokeRefreshToken(userId, refreshToken);
}
</code></pre>
<h2 id="heading-3-broken-object-property-level-authorization-bopla">3. Broken Object Property Level Authorization (BOPLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>The API returns more data than the user needs. Internal flags, admin permissions, and sensitive fields that should never leave the server end up in the response payload. Or worse: the API accepts more data than the user should be able to set, allowing users to modify fields they should never touch.</p>
<p>A user fetches their profile and the response includes <code>isAdmin: false</code>, <code>internalAccountScore: 742</code>, or <code>fraudRiskLevel: "low"</code>. None of these should ever be in a user-facing response.</p>
<p>Or a user updates their profile and the request body includes <code>"role": "admin"</code>. The API processes it. The user has just promoted themselves to admin.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>This is a structure problem. It happens when systems are built without a deliberately designed response schema. Some developers return the raw database entity directly because it's easier. Some lack the domain knowledge to properly structure their data layer. The result is that internal data leaks into external responses.</p>
<p>This is also an Interface Segregation Principle violation. The response interface forces the consumer to receive data it should never have access to.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every API endpoint must have an explicit, deliberately designed response DTO. The response DTO contains only the fields the caller is authorized to receive. The domain entity never travels directly to the response.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">//Wrong returning the domain entity directly - exposes internal fields
Future&lt;Response&gt; getProfile(Request request) async {
  final user = await _userRepository.findById(userId);
  return Response.ok(jsonEncode(user.toJson())); // exposes everything
}

// Correct : explicit response DTO — only what the caller should see
class UserProfileResponse {
  final String id;
  final String firstName;
  final String lastName;
  final String email;

  const UserProfileResponse({
    required this.id,
    required this.firstName,
    required this.lastName,
    required this.email,
  });

  Map&lt;String, dynamic&gt; toJson() =&gt; {
    'id': id,
    'first_name': firstName,
    'last_name': lastName,
    'email': email,
    // isAdmin, internalScore, fraudRiskLevel — never here
  };
}

Future&lt;Response&gt; getProfile(Request request) async {
  final user = await _userRepository.findById(userId);

  final response = UserProfileResponse(
    id: user.id,
    firstName: user.firstName,
    lastName: user.lastName,
    email: user.email,
  );

  return Response.ok(jsonEncode(response.toJson()));
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// Wrong = returning the domain model directly
public async Task&lt;IActionResult&gt; GetProfile(string userId)
{
    var user = await _repository.FindByIdAsync(userId);
    return Ok(user); 
}

// Correct explicit response DTO
public record UserProfileResponse(
    string Id,
    string FirstName,
    string LastName,
    string Email);

public async Task&lt;IActionResult&gt; GetProfile(string userId)
{
    var user = await _repository.FindByIdAsync(userId);

    var response = new UserProfileResponse(
        user.Id,
        user.FirstName,
        user.LastName,
        user.Email
        // IsAdmin, InternalScore, FraudRiskLevel — never exposed
    );

    return Ok(response);
}
</code></pre>
<p>For incoming requests, use a request DTO that only accepts the fields a user is permitted to modify. Never bind directly to a domain entity in an update operation.</p>
<h2 id="heading-4-unrestricted-resource-consumption">4. Unrestricted Resource Consumption</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>No rate limiting. A caller can spam critical APIs thousands of times per minute, such as with scraping, brute forcing, or denial of service attacks. The API accepts every request without any throttling or limit on consumption.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Rate limiting is treated as optional or as a future concern. It's deferred to "when we need to scale" or "when we see abuse." By the time abuse is visible, the damage is already happening. A financial API without rate limiting can be brute-forced for valid account numbers, scraped for pricing data, or simply overwhelmed into unavailability.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Rate limiting must be implemented at the API gateway layer, before requests reach the service layer. This isn't a service responsibility. The gateway is the right enforcement point because it can handle this for all services simultaneously without each service reimplementing it.</p>
<p>Different endpoints need different limits. Authentication endpoints need strict limits (5 attempts per 5 minutes per IP). Public read endpoints need moderate limits. Write operations on sensitive resources need strict limits.</p>
<p><strong>Dart (middleware approach):</strong></p>
<pre><code class="language-dart">class RateLimitMiddleware {
  final RateLimiter _limiter;

  RateLimitMiddleware(this._limiter);

  Handler call(Handler innerHandler) {
    return (Request request) async {
      final clientIp = request.headers['x-forwarded-for'] ?? 'unknown';
      final endpoint = request.url.path;

      final limit = _getLimitForEndpoint(endpoint);
      final isAllowed = await _limiter.checkLimit(
        key: '$clientIp:$endpoint',
        maxRequests: limit.maxRequests,
        windowSeconds: limit.windowSeconds,
      );

      if (!isAllowed) {
        return Response(
          429,
          body: jsonEncode({'error': 'Rate limit exceeded'}),
          headers: {'Retry-After': '60'},
        );
      }

      return innerHandler(request);
    };
  }

  RateLimit _getLimitForEndpoint(String path) {
    if (path.contains('/auth/login')) {
      return RateLimit(maxRequests: 5, windowSeconds: 300);
    }
    if (path.contains('/transactions')) {
      return RateLimit(maxRequests: 100, windowSeconds: 60);
    }
    return RateLimit(maxRequests: 1000, windowSeconds: 60);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// using AspNetCoreRateLimit
builder.Services.AddRateLimiter(options =&gt;
{
    options.AddFixedWindowLimiter("auth", limiterOptions =&gt;
    {
        limiterOptions.PermitLimit = 5;
        limiterOptions.Window = TimeSpan.FromMinutes(5);
        limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        limiterOptions.QueueLimit = 0;
    });

    options.AddFixedWindowLimiter("standard", limiterOptions =&gt;
    {
        limiterOptions.PermitLimit = 100;
        limiterOptions.Window = TimeSpan.FromMinutes(1);
    });

    options.RejectionStatusCode = 429;
});

// apply per controller
[EnableRateLimiting("auth")]
[HttpPost("login")]
public async Task&lt;IActionResult&gt; Login(LoginRequest request) { }

[EnableRateLimiting("standard")]
[HttpGet("transactions")]
public async Task&lt;IActionResult&gt; GetTransactions() { }
</code></pre>
<h2 id="heading-5-broken-function-level-authorization-bfla">5. Broken Function Level Authorization (BFLA)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A regular user gets access to functions or endpoints that should only be accessible to admins or privileged roles. The frontend hides the button, but the endpoint is still there, wide open.</p>
<p>A regular user token is used to call an admin endpoint. It works. The attacker now has admin functionality with a non-admin account.</p>
<p>Security through obscurity is not security. Hiding admin resources at the UI level doesn't equal security.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>RBAC (Role-Based Access Control) is either not implemented or implemented incorrectly. Authorization checks are missing at the function level. The assumption is that if a user can't see the admin button in the UI, they can't call the admin API. This assumption is always wrong. Any developer tool can call any API endpoint directly, bypassing the UI entirely.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every function must check the caller's role before executing. This check must happen in the service layer, not the UI layer, and not the API gateway alone. The gateway can verify that a token is valid. Only the service layer knows what roles are required for each specific operation.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class UserManagementService {
  final AuthContext _authContext;
  final UserRepository _repository;

  UserManagementService(this._authContext, this._repository);

  Future&lt;Result&lt;void, AppException&gt;&gt; deleteUser(String targetUserId) async {
    final currentUser = _authContext.currentUser;

    // role check - this must happen in the service layer
    if (!currentUser.hasRole(UserRole.admin)) {
      return Result.failure(
        AppException.forbidden('Admin role required for this operation'),
      );
    }

    await _repository.deleteUser(targetUserId);
    return Result.success(null);
  }

  Future&lt;Result&lt;List&lt;User&gt;, AppException&gt;&gt; getAllUsers() async {
    final currentUser = _authContext.currentUser;

    if (!currentUser.hasRole(UserRole.admin)) {
      return Result.failure(
        AppException.forbidden('Admin role required'),
      );
    }

    final users = await _repository.findAll();
    return Result.success(users);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">[ApiController]
[Route("api/admin/users")]
[Authorize]
public class UserManagementController : ControllerBase
{
    private readonly IUserManagementService _service;

    [HttpDelete("{userId}")]
    [Authorize(Roles = "Admin")] 
    public async Task&lt;IActionResult&gt; DeleteUser(string userId)
    {
        await _service.DeleteUser(userId);
        return NoContent();
    }

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public async Task&lt;IActionResult&gt; GetAllUsers()
    {
        var users = await _service.GetAllUsers();
        return Ok(users);
    }
}
</code></pre>
<p>Role checks at the attribute level in C# and explicit role validation in the service layer in Dart both achieve the same thing: the check happens in code, not in the UI, and not in the API consumer's behavior.</p>
<h2 id="heading-6-unrestricted-access-to-sensitive-business-flows">6. Unrestricted Access to Sensitive Business Flows</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Core business logic that should have strict guardrails has none. Users can bypass business rules and trigger flows that should never be allowed in their situation.</p>
<p>A sales agent creates a sale for a customer in an area that doesn't have coverage. The endpoint that creates the sale never verified that coverage exists. A business rule was violated. In financial terms, this causes loss. In operational terms, this causes the kind of problems that take months to untangle.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>Business logic isn't identified and isn't enforced at the domain layer. Domain-Driven Design exists precisely for this reason: business logic breaks or makes your application. When the domain layer isn't properly designed, and business rules aren't explicitly encoded, users can bypass them.</p>
<p>The guardrails are missing because the engineers didn't know the guardrails were supposed to exist there. This is a domain knowledge problem as much as a technical problem.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Business rules belong in the domain layer. This is what Value Objects and domain entities enforce. A sale can't be created unless coverage is confirmed. That rule is encoded into the domain, not into the API endpoint or the UI.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class Sale {
  final String agentId;
  final String customerId;
  final CoverageArea coverageArea;
  final SaleStatus status;

  Sale._({
    required this.agentId,
    required this.customerId,
    required this.coverageArea,
    required this.status,
  });

  // business rule enforced at domain creation - no coverage, no sale
  static Result&lt;Sale, DomainException&gt; create({
    required String agentId,
    required String customerId,
    required CoverageArea coverageArea,
  }) {
    if (!coverageArea.hasActiveCoverage) {
      return Result.failure(
        DomainException('Cannot create sale: customer area has no active coverage'),
      );
    }

    return Result.success(Sale._(
      agentId: agentId,
      customerId: customerId,
      coverageArea: coverageArea,
      status: SaleStatus.pending,
    ));
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class Sale
{
    private Sale(string agentId, string customerId, CoverageArea area)
    {
        AgentId = agentId;
        CustomerId = customerId;
        CoverageArea = area;
        Status = SaleStatus.Pending;
    }

    public string AgentId { get; }
    public string CustomerId { get; }
    public CoverageArea CoverageArea { get; }
    public SaleStatus Status { get; private set; }

    // factory enforces the business rule no coverage, no sale
    public static Result&lt;Sale&gt; Create(
        string agentId,
        string customerId,
        CoverageArea coverageArea)
    {
        if (!coverageArea.HasActiveCoverage)
            return Result.Failure&lt;Sale&gt;(
                "Cannot create sale: no active coverage in this area");

        return Result.Success(new Sale(agentId, customerId, coverageArea));
    }
}
</code></pre>
<p>The endpoint that creates a sale calls the domain factory. The domain factory enforces the business rule. The rule can't be bypassed through the API because the API can't create a Sale that bypasses the factory.</p>
<h2 id="heading-7-security-misconfiguration">7. Security Misconfiguration</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>A developer's personal debugging process shipped to production. Verbose error messages exposing stack traces. Debug endpoints left active. Permissive CORS allowing any origin. Sensitive data in logs. The developer's local configuration running in a production environment.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>These types of issues tend to happen when there's no separation between development, staging, and production configurations. There's no pipeline gate that catches misconfiguration before it reaches production. Each developer manages their own configuration, which means every developer's habits and debugging preferences can end up in production.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Set up different workflows for every environment. The production pipeline must include static analysis, configuration validation, and linting that catches debug endpoints, permissive CORS, verbose error logging, and exposed secrets before a merge is allowed.</p>
<p><strong>Dart (environment-aware error handling):</strong></p>
<pre><code class="language-dart">class ErrorHandler {
  final Environment _environment;

  ErrorHandler(this._environment);

  Response handleException(Object error, StackTrace stackTrace) {
 
    logger.error('Unhandled exception', error: error, stackTrace: stackTrace);

    if (_environment.isProduction) {
      
      return Response.internalServerError(
        body: jsonEncode({'error': 'An internal error occurred'}),
      );
    }

    
    return Response.internalServerError(
      body: jsonEncode({
        'error': error.toString(),
        'stackTrace': stackTrace.toString(),
      }),
    );
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">
app.UseExceptionHandler(errorApp =&gt;
{
    errorApp.Run(async context =&gt;
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/json";

        var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
        if (error != null)
        {
            // log internally with full details
            logger.LogError(error.Error, "Unhandled exception");
        }

        // return generic message to caller
        await context.Response.WriteAsync(
            JsonSerializer.Serialize(new { error = "An internal error occurred" })
        );
    });
});

// CORS - explicit allowed origins, never wildcard in production
builder.Services.AddCors(options =&gt;
{
    options.AddPolicy("ProductionPolicy", policy =&gt;
    {
        policy.WithOrigins(
            "https://app.yourproduct.com",
            "https://admin.yourproduct.com"
        )
        .AllowedMethods("GET", "POST", "PUT", "DELETE")
        .AllowedHeaders("Authorization", "Content-Type");
        
    });
});
</code></pre>
<p>CORS in production must use explicit allowed origins. Wildcard CORS in production is a direct security failure that allows any web page on the internet to make authenticated requests to your API using the visitor's credentials.</p>
<h2 id="heading-8-improper-inventory-management">8. Improper Inventory Management</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Deprecated APIs, decommissioned endpoints, and outdated API versions still running on the server. Nobody knows they exist and nobody owns them. But attackers find them and exploit them because old endpoints are often less secured than current ones.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>API lifecycle management is nobody's formal responsibility. Endpoints get created and features change. The old endpoint version is forgotten rather than retired. Over time, the API surface area grows with dead endpoints that still respond to requests, often without the security controls applied to newer endpoints.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Someone must own the API inventory. This is a formal engineering responsibility, not an optional practice. Every API endpoint must be documented, versioned, and have a defined lifecycle: active, deprecated, or decommissioned.</p>
<p>Deprecated endpoints should return a response header indicating their deprecation date. Decommissioned endpoints must return 410 Gone, not continue to process requests.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">// deprecated endpoint wrapper
Handler deprecatedEndpoint({
  required Handler handler,
  required DateTime removalDate,
  required String replacementEndpoint,
}) {
  return (Request request) async {
    final response = await handler(request);

    // add deprecation headers so clients know to migrate
    return response.change(headers: {
      'Deprecation': 'true',
      'Sunset': HttpDate.format(removalDate),
      'Link': '&lt;$replacementEndpoint&gt;; rel="successor-version"',
      'Warning': '299 - "This endpoint is deprecated and will be removed on ${removalDate.toIso8601String()}"',
    });
  };
}

// decommissioned endpoint
Future&lt;Response&gt; decommissionedEndpoint(Request request) async {
  return Response(
    410,
    body: jsonEncode({
      'error': 'This endpoint has been permanently removed',
      'replacement': '/api/v2/accounts',
    }),
  );
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// mark endpoints as deprecated using ApiVersion attributes
[ApiController]
[ApiVersion("1.0", Deprecated = true)]
[Route("api/v{version:apiVersion}/accounts")]
public class AccountsV1Controller : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetAccount(string id)
    {
        Response.Headers.Add("Deprecation", "true");
        Response.Headers.Add("Sunset", "Sat, 01 Jan 2027 00:00:00 GMT");
        Response.Headers.Add("Link", "&lt;/api/v2/accounts/{id}&gt;; rel=\"successor-version\"");

        // still process the request during deprecation period
        return Ok(_service.GetAccount(id));
    }
}

// gone - permanent removal
[ApiController]
[Route("api/v1/legacy/accounts")]
public class LegacyAccountsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll()
    {
        return StatusCode(410, new { error = "This endpoint has been permanently removed", replacement = "/api/v2/accounts" });
    }
}
</code></pre>
<h2 id="heading-9-unsafe-consumption-of-apis">9. Unsafe Consumption of APIs</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>Your application integrates with third-party services and trusts their data without validation or guardrails. Whatever the external API returns, your application processes it directly.</p>
<p>A third-party payment callback returns a transaction status. Your application trusts it without verifying the signature or validating the data structure. An attacker sends a forged callback to your callback URL. Your application processes it as legitimate.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>External services are treated as trusted by default. There's no defined contract for what valid data from an external service looks like. There's no validation layer between the external service response and the application's processing logic.</p>
<p>Trust is assumed rather than verified.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Every integration with an external service must have a defined contract. The contract specifies what valid data looks like, what fields are required, and what the valid ranges and formats are. Every response from an external service is validated against this contract before any processing happens.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class PaymentCallbackService {
  final String _webhookSecret;

  PaymentCallbackService(this._webhookSecret);

  Future&lt;Result&lt;PaymentStatus, AppException&gt;&gt; processCallback(
    Map&lt;String, dynamic&gt; payload,
    String signature,
    String rawBody,
  ) async {
    // step 1: verify the signature before processing anything
    final isValid = _verifySignature(rawBody, signature, _webhookSecret);
    if (!isValid) {
      logger.warning('Invalid webhook signature received');
      return Result.failure(
        AppException.unauthorized('Invalid webhook signature'),
      );
    }

    // step 2: validate the payload structure against our contract
    final validationResult = _validateCallbackPayload(payload);
    if (validationResult.isFailure) {
      logger.warning('Invalid callback payload: ${validationResult.error}');
      return Result.failure(validationResult.error!);
    }

    // step 3: only now do we trust and process the data
    final status = PaymentStatus.fromString(payload['status'] as String);
    return Result.success(status);
  }

  bool _verifySignature(String body, String signature, String secret) {
    final hmac = Hmac(sha256, utf8.encode(secret));
    final digest = hmac.convert(utf8.encode(body));
    final expectedSignature = 'sha256=${base64.encode(digest.bytes)}';
    return expectedSignature == signature;
  }

  Result&lt;void, AppException&gt; _validateCallbackPayload(
    Map&lt;String, dynamic&gt; payload,
  ) {
    if (!payload.containsKey('transaction_id')) {
      return Result.failure(
        AppException.validation('Missing required field: transaction_id'),
      );
    }
    if (!payload.containsKey('status')) {
      return Result.failure(
        AppException.validation('Missing required field: status'),
      );
    }
    final validStatuses = {'success', 'failed', 'pending'};
    if (!validStatuses.contains(payload['status'])) {
      return Result.failure(
        AppException.validation('Invalid status value: ${payload['status']}'),
      );
    }
    return Result.success(null);
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class PaymentCallbackService
{
    private readonly string _webhookSecret;
    private readonly ILogger&lt;PaymentCallbackService&gt; _logger;

    public async Task&lt;Result&lt;PaymentStatus&gt;&gt; ProcessCallback(
        string rawBody,
        string signature,
        PaymentCallbackDto payload)
    {
        // verify signature first
        if (!VerifySignature(rawBody, signature))
        {
            _logger.LogWarning("Invalid webhook signature received");
            return Result.Failure&lt;PaymentStatus&gt;("Invalid webhook signature");
        }

        // validate payload
        if (string.IsNullOrEmpty(payload.TransactionId))
            return Result.Failure&lt;PaymentStatus&gt;("Missing transaction_id");

        var validStatuses = new[] { "success", "failed", "pending" };
        if (!validStatuses.Contains(payload.Status))
            return Result.Failure&lt;PaymentStatus&gt;($"Invalid status: {payload.Status}");

        return Result.Success(Enum.Parse&lt;PaymentStatus&gt;(payload.Status, true));
    }

    private bool VerifySignature(string body, string signature)
    {
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_webhookSecret));
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(body));
        var expectedSignature = $"sha256={Convert.ToBase64String(hash)}";
        return CryptographicOperations.FixedTimeEquals(
            Encoding.UTF8.GetBytes(expectedSignature),
            Encoding.UTF8.GetBytes(signature)
        );
    }
}
</code></pre>
<p>It must be a standard of engineering to create verified contracts with external services before integration begins. Never trust, always verify.</p>
<h2 id="heading-10-server-side-request-forgery-ssrf">10. Server-Side Request Forgery (SSRF)</h2>
<h3 id="heading-what-it-is">What it is</h3>
<p>An API accepts a URL as input and makes a server-side request to that URL. An attacker provides a URL that points to internal infrastructure: <code>http://169.254.169.254/latest/meta-data/</code> (AWS metadata service), <code>http://internal-database:5432</code>, or <code>http://admin-panel.internal</code>. The server makes the request from inside the network, bypassing external firewalls.</p>
<p>Most payment systems take callback URLs or redirect URLs in the request. If the API forwards requests to those URLs without validation, it will happily make requests to internal infrastructure on behalf of the attacker.</p>
<h3 id="heading-the-engineering-failure">The Engineering Failure</h3>
<p>This is a design flaw that must be caught at the architectural layer, not the code layer. Any API that accepts URLs as input and makes server-side requests to those URLs is a potential SSRF target. The design decision to accept arbitrary URLs must come with the design decision to strictly validate those URLs.</p>
<h3 id="heading-the-engineering-fix">The Engineering Fix</h3>
<p>Any API that accepts a URL must validate it against a list of allowed domains before making any request. This is a design decision. The allowlist is part of the API's specification, not an afterthought.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">class WebhookService {
  // only these domains are allowed to receive callbacks
  static const _allowedDomains = {
    'api.yourpartner.com',
    'hooks.yourintegration.com',
    'callbacks.trustedservice.io',
  };

  Future&lt;Result&lt;void, AppException&gt;&gt; registerCallbackUrl(String url) async {
    // validate before storing or using
    final validationResult = _validateCallbackUrl(url);
    if (validationResult.isFailure) {
      return Result.failure(validationResult.error!);
    }

    await _webhookRepository.save(url);
    return Result.success(null);
  }

  Result&lt;void, AppException&gt; _validateCallbackUrl(String url) {
    final uri = Uri.tryParse(url);

    if (uri == null) {
      return Result.failure(AppException.validation('Invalid URL format'));
    }

    // must be HTTPS in production
    if (uri.scheme != 'https') {
      return Result.failure(
        AppException.validation('Callback URL must use HTTPS'),
      );
    }

    // must be in the allowlist
    if (!_allowedDomains.contains(uri.host)) {
      return Result.failure(
        AppException.validation(
          'Callback URL domain is not in the approved list',
        ),
      );
    }

    // block internal IP ranges explicitly
    if (_isInternalAddress(uri.host)) {
      return Result.failure(
        AppException.validation('Callback URL cannot point to internal addresses'),
      );
    }

    return Result.success(null);
  }

  bool _isInternalAddress(String host) {
    final privateRanges = [
      '127.', '10.', '172.16.', '172.17.', '172.18.',
      '192.168.', '169.254.', 'localhost', '0.0.0.0',
    ];
    return privateRanges.any((range) =&gt; host.startsWith(range));
  }
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">public class WebhookService
{
    private static readonly HashSet&lt;string&gt; AllowedDomains = new()
    {
        "api.yourpartner.com",
        "hooks.yourintegration.com",
        "callbacks.trustedservice.io"
    };

    public async Task&lt;Result&lt;bool&gt;&gt; RegisterCallbackUrl(string url)
    {
        var validationResult = ValidateCallbackUrl(url);
        if (!validationResult.IsSuccess)
            return Result.Failure&lt;bool&gt;(validationResult.Error);

        await _repository.SaveCallbackUrl(url);
        return Result.Success(true);
    }

    private Result&lt;bool&gt; ValidateCallbackUrl(string url)
    {
        if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
            return Result.Failure&lt;bool&gt;("Invalid URL format");

        if (uri.Scheme != "https")
            return Result.Failure&lt;bool&gt;("Callback URL must use HTTPS");

        if (!AllowedDomains.Contains(uri.Host))
            return Result.Failure&lt;bool&gt;("Domain not in approved list");

        if (IsInternalAddress(uri.Host))
            return Result.Failure&lt;bool&gt;("Internal addresses are not permitted");

        return Result.Success(true);
    }

    private bool IsInternalAddress(string host)
    {
        var internalPrefixes = new[]
        {
            "127.", "10.", "172.16.", "192.168.",
            "169.254.", "localhost", "0.0.0.0"
        };
        return internalPrefixes.Any(p =&gt; host.StartsWith(p));
    }
}
</code></pre>
<h2 id="heading-engineering-vulnerabilities-beyond-the-owasp-list">Engineering Vulnerabilities Beyond the OWASP List</h2>
<p>The OWASP list covers the most critical and most common API vulnerabilities. But engineering experience surfaces additional patterns that can create serious security gaps.</p>
<h3 id="heading-apis-called-by-multiple-clients-without-domain-allowlisting">APIs Called by Multiple Clients Without Domain Allowlisting</h3>
<p>Some APIs called by multiple clients don't enforce which domains are allowed to call them. This makes it possible for people to share API keys and access resources from unauthorized origins.</p>
<p>In large-scale organizations, this is a major security gap that often goes unnoticed because the API technically works correctly from every client.</p>
<p>The fix: every API that accepts an API key must also validate the calling domain. API keys and allowed domains must be explicitly paired.</p>
<h3 id="heading-exposing-secrets-in-code-and-logs">Exposing Secrets in Code and Logs</h3>
<p>A developer leaves secret keys, public keys, and credentials in their code, in their repository, or on their machine. Adding files to <code>.gitignore</code> isn't enough. These datasets must be fetched from a trusted secrets manager at runtime, never stored in source code.</p>
<p>Organizations must use vaults, Azure App Configuration, AWS Secrets Manager, or equivalent systems. This must be an engineering standard, not a developer preference. The vault access pattern must be standardized so developers don't have to figure this out per project.</p>
<h3 id="heading-microservices-talking-to-each-other-without-a-gateway">Microservices Talking to Each Other Without a Gateway</h3>
<p>If you are building microservices, every communication between services must be treated as sensitive. There must be an API gateway that handles authentication for all services. Services must not trust each other implicitly. Every inter-service call must be authenticated.</p>
<p>Communication between microservices should use event brokers like Kafka for asynchronous flows, or mTLS for synchronous flows. No microservice should be directly accessible from the internet without going through the gateway.</p>
<h3 id="heading-encryption-without-organizational-standards">Encryption Without Organizational Standards</h3>
<p>Organizations must have standardized encryption algorithms. Not developer-chosen algorithms, not algorithm-of-the-week, and not whatever the developer found in a Stack Overflow answer. A staff-level engineering decision must specify which algorithm, which mode, and which key length is the organizational standard.</p>
<p>The vulnerabilities that come from ad-hoc encryption choices are serious: padding oracle attacks, weak key lengths, IV reuse, and stack traces during encryption failures that reveal internal implementation details to callers.</p>
<p>The engineering control: expose internally built packages or cloud functions for encryption that projects import rather than implement. Developers use the package. They never write encryption from scratch per project.</p>
<h3 id="heading-sql-injection">SQL Injection</h3>
<p>SQL injection is 25 years old. It's been in existence since 1998. But it still happens because engineering standards aren't enforced.</p>
<p>It happens because developers build queries with string concatenation, taking user input and gluing it into a SQL string. The fix is parameterized queries or prepared statements, always. Raw SQL strings with user input concatenated are never acceptable.</p>
<p><strong>Dart:</strong></p>
<pre><code class="language-dart">//Wrong  string concatenation — SQL injection vulnerability
Future&lt;User?&gt; findUser(String email) async {
  final query = "SELECT * FROM users WHERE email = '$email'";
  // attacker passes: admin@example.com' OR '1'='1
  // query becomes: SELECT * FROM users WHERE email = 'admin@example.com' OR '1'='1'
  // returns all users
  return await database.rawQuery(query);
}

// parameterized query — injection proof
Future&lt;User?&gt; findUser(String email) async {
  final results = await database.query(
    'users',
    where: 'email = ?',    
    whereArgs: [email],     
  );
  return results.isNotEmpty ? User.fromMap(results.first) : null;
}
</code></pre>
<p><strong>C#:</strong></p>
<pre><code class="language-csharp">// Wrong string concatenation
public async Task&lt;User?&gt; FindUser(string email)
{
    var query = $"SELECT * FROM Users WHERE Email = '{email}'";
    return await _context.Users.FromSqlRaw(query).FirstOrDefaultAsync();
}

// Correct parameterized query using EF Core
public async Task&lt;User?&gt; FindUser(string email)
{
    return await _context.Users
        .Where(u =&gt; u.Email == email)
        .FirstOrDefaultAsync();
}

// Correct parameterized raw SQL when needed
public async Task&lt;User?&gt; FindUserRaw(string email)
{
    return await _context.Users
        .FromSqlRaw("SELECT * FROM Users WHERE Email = {0}", email)
        .FirstOrDefaultAsync();
}
</code></pre>
<p>This is a major vulnerability that comes from core engineering decisions that should be under strict governance and compliance principles. These principles help establish development standards on projects and in organizations.</p>
<p>This could also be enforced at CI CD level. If static analysis in the CI/CD pipeline doesn't catch raw SQL string concatenation, your team should add it. This is a vulnerability class that should never reach production.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Every vulnerability in this list has one thing in common: it was preventable. Not by security tools applied after the fact, but by engineering discipline applied during design and development.</p>
<ul>
<li><p>BOLA is prevented by ID-aware authorization in the service layer.</p>
</li>
<li><p>Broken authentication is prevented by proper token design and rate limiting.</p>
</li>
<li><p>BOPLA is prevented by explicit response DTOs.</p>
</li>
<li><p>Unrestricted resource consumption is prevented by rate limiting at the gateway.</p>
</li>
<li><p>BFLA is prevented by role checks in code, not in the UI.</p>
</li>
<li><p>Sensitive business flow exposure is prevented by domain-driven design and proper business rule enforcement.</p>
</li>
<li><p>Security misconfiguration is prevented by environment-specific pipelines with automated gates.</p>
</li>
<li><p>Improper inventory management is prevented by formal API lifecycle ownership.</p>
</li>
<li><p>Unsafe API consumption is prevented by contract-first external integrations.</p>
</li>
<li><p>SSRF is prevented by URL allowlisting as a design decision.</p>
</li>
</ul>
<p>The pattern is consistent. Security isn't something you add to an application. It's something you engineer into the architecture from the beginning. Every decision in this article is an engineering decision: where does this check belong in the architecture? Which layer is responsible for this validation? What does the domain enforce? What does the gateway enforce? What does the pipeline catch?</p>
<p>Security by design isn't a security team's responsibility. It's an engineering team's responsibility. And it starts with understanding exactly what these vulnerabilities are, where they come from, and what the engineering standard is to prevent them.</p>
<p>As software engineers, this kind of next level thinking ensures our code doesn't fail these security tests.</p>
<p>Happy Secured Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Fix Common Web Application Security Vulnerabilities in Node.js ]]>
                </title>
                <description>
                    <![CDATA[ Here's something that tends to surprise developers who are new to security: most web vulnerabilities aren't the result of sophisticated attacks. They come from code patterns that look completely reaso ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-fix-common-web-application-security-vulnerabilities-in-node-js/</link>
                <guid isPermaLink="false">6a581c65dba34eeb664be8e2</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ owasp ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hackita ]]>
                </dc:creator>
                <pubDate>Wed, 15 Jul 2026 23:48:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/b2ec81b6-d6eb-41f0-9fa5-7570914ef97d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Here's something that tends to surprise developers who are new to security: most web vulnerabilities aren't the result of sophisticated attacks. They come from code patterns that look completely reasonable: trusting a value from the URL, applying a request body to a database update, or running two queries where one should've been enough.</p>
<p>This guide covers six of those patterns. For each one, you'll see a real code example that creates the vulnerability, an explanation of what makes it dangerous, and a corrected version with notes on exactly what changed and why.</p>
<p>No security background is required to follow along here. It'll just help to have some familiarity with Node.js and SQL.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>The examples assume you're comfortable with:</p>
<ul>
<li><p>Node.js and Express.js basics</p>
</li>
<li><p>SQL queries</p>
</li>
<li><p>How HTTP requests and responses work</p>
</li>
<li><p>Basic authentication concepts (sessions, tokens)</p>
</li>
</ul>
<p><strong>Note on code examples</strong>: Throughout this tutorial, <code>db.query()</code> is a fictional database helper that returns a single row object for <code>SELECT</code> queries (or <code>null</code> if not found), and a result object for <code>INSERT</code>/<code>UPDATE</code> queries. The <code>connection.query()</code> in the race conditions section uses the <a href="https://github.com/sidorares/node-mysql2">mysql2</a> promise API directly, where <code>query()</code> returns <code>[rows, fields]</code>. Adapt the syntax to the database driver you use.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-1-broken-access-control-and-idor">1. Broken Access Control and IDOR</a></p>
</li>
<li><p><a href="#heading-2-mass-assignment">2. Mass Assignment</a></p>
</li>
<li><p><a href="#heading-3-prototype-pollution">3. Prototype Pollution</a></p>
</li>
<li><p><a href="#heading-4-race-conditions">4. Race Conditions</a></p>
</li>
<li><p><a href="#heading-5-business-logic-flaws">5. Business Logic Flaws</a></p>
</li>
<li><p><a href="#heading-6-jwt-misconfiguration">6. JWT Misconfiguration</a></p>
</li>
<li><p><a href="#heading-summary">Summary</a></p>
</li>
</ul>
<h2 id="heading-1-broken-access-control-and-idor">1. Broken Access Control and IDOR</h2>
<p><a href="https://owasp.org/Top10/A01_2021-Broken_Access_Control/">Broken Access Control</a> has topped the OWASP Top 10 since 2021, and it's not hard to see why. The most common form is <strong>Insecure Direct Object Reference (IDOR)</strong>: the application exposes a database ID in a URL, a user changes the number, and suddenly they're looking at someone else's data.</p>
<p>The fix seems obvious in hindsight. But it keeps appearing in production code because authentication and authorization get conflated. Confirming that a user is logged in is not the same as confirming they're allowed to access a specific resource.</p>
<h3 id="heading-how-to-identify-this-vulnerability-in-your-code">How to Identify This Vulnerability in Your Code</h3>
<p>Here's a typical user profile endpoint:</p>
<pre><code class="language-javascript">// Express.js - Vulnerable
app.get('/api/users/:id/profile', authenticate, async (req, res) =&gt; {
  const userId = req.params.id;

  const user = await db.query(
    'SELECT id, name, email, address FROM users WHERE id = ?',
    [userId]
  );

  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  res.json(user);
});
</code></pre>
<p>The <code>authenticate</code> middleware confirms that the request includes a valid token. But it doesn't confirm whether the authenticated user is allowed to access the requested resource.</p>
<p>Any authenticated user can request <code>/api/users/1/profile</code>, <code>/api/users/2/profile</code>, and so on and retrieve other users' data.</p>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>Authentication confirms <em>who</em> you are. Authorization confirms <em>what you're allowed to do</em>. The code above does the first and skips the second entirely.</p>
<p>With a sequential numeric ID, a curious user doesn't need any special tools. They can just change <code>1</code> to <code>2</code> in the URL. But the same problem exists with UUIDs or slugs if the ownership check is missing.</p>
<h3 id="heading-how-to-fix-this-vulnerability">How to Fix This Vulnerability</h3>
<p>Verify server-side that the authenticated user owns — or is explicitly authorized to access — the requested resource:</p>
<pre><code class="language-javascript">// Express.js - Secure
app.get('/api/users/:id/profile', authenticate, async (req, res) =&gt; {
  // Reject anything that isn't a string of digits — parseInt("12abc") would return 12
  if (!/^\d+$/.test(req.params.id)) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }

  const requestedId = Number(req.params.id);

  if (requestedId &lt; 1) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }

  // The authenticated user's ID is set by the authenticate middleware
  const authenticatedId = req.user.id;

  // Enforce ownership: users can only access their own profile
  if (requestedId !== authenticatedId) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  const user = await db.query(
    'SELECT id, name, email, address FROM users WHERE id = ?',
    [requestedId]
  );

  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  res.json(user);
});
</code></pre>
<p>For admin endpoints that legitimately need to access any user, enforce role-based authorization explicitly:</p>
<pre><code class="language-javascript">// Admin endpoint with explicit role check
app.get('/api/admin/users/:id', authenticate, requireRole('admin'), async (req, res) =&gt; {
  if (!/^\d+$/.test(req.params.id)) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }

  const userId = Number(req.params.id);

  const user = await db.query(
    'SELECT id, name, email, role FROM users WHERE id = ?',
    [userId]
  );

  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }

  res.json(user);
});
</code></pre>
<p>Here's what changed and why:</p>
<ul>
<li><p><code>/^\d+$/.test(req.params.id)</code> rejects anything that isn't a pure string of digits. <code>parseInt("12abc", 10)</code> would silently return <code>12</code> and pass further checks. The regex prevents this.</p>
</li>
<li><p><code>Number(req.params.id)</code> converts the already-validated string to a number safely.</p>
</li>
<li><p>The comparison <code>requestedId !== authenticatedId</code> enforces ownership.</p>
</li>
<li><p>Admin functionality is a separate endpoint with its own authorization check.</p>
</li>
</ul>
<p><strong>Never infer authorization from a URL parameter. Derive it from the authenticated session.</strong></p>
<h2 id="heading-2-mass-assignment">2. Mass Assignment</h2>
<p>Mass assignment is one of those vulnerabilities that's almost invisible when you write it. You're just being efficient, right? Why iterate over fields manually when you can pass the whole object?</p>
<p>The problem is that your database table knows about fields your users were never supposed to touch.</p>
<h3 id="heading-how-to-identify-this-vulnerability-in-your-code">How to Identify This Vulnerability in Your Code</h3>
<p>Here's a user profile update endpoint:</p>
<pre><code class="language-javascript">// Express.js - Vulnerable
app.put('/api/users/me', authenticate, async (req, res) =&gt; {
  const userId = req.user.id;

  // req.body contains everything the client sends
  const updates = req.body;

  await db.query(
    'UPDATE users SET ? WHERE id = ?',
    [updates, userId]
  );

  res.json({ success: true });
});
</code></pre>
<p>The <code>users</code> table has these columns:</p>
<pre><code class="language-sql">CREATE TABLE users (
  id           INT PRIMARY KEY,
  name         VARCHAR(100),
  email        VARCHAR(100),
  bio          TEXT,
  role         ENUM('user', 'moderator', 'admin') DEFAULT 'user',
  credits      INT DEFAULT 0,
  is_banned    BOOLEAN DEFAULT false
);
</code></pre>
<p>The developer intended users to update <code>name</code>, <code>email</code>, and <code>bio</code>. But <code>role</code>, <code>credits</code>, and <code>is_banned</code> are also in the table — and the query updates whatever fields the client sends.</p>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>That request body goes straight into the SQL query. The <code>users</code> table also has <code>role</code>, <code>credits</code>, and <code>is_banned</code> — and the query doesn't know or care which fields the developer "intended" to expose.</p>
<p>A user who sends this:</p>
<pre><code class="language-json">{
  "name": "Alice",
  "role": "admin",
  "credits": 100000,
  "is_banned": false
}
</code></pre>
<p>Has just promoted themselves to admin, cleared their ban, and given themselves a hundred thousand credits.</p>
<h3 id="heading-how-to-fix-this-vulnerability">How to Fix This Vulnerability</h3>
<p>Build the update object yourself, field by field, using an explicit allowlist:</p>
<pre><code class="language-javascript">// Express.js - Secure
app.put('/api/users/me', authenticate, async (req, res) =&gt; {
  const userId = req.user.id;

  // Only these fields may be updated by the user
  const ALLOWED_FIELDS = ['name', 'email', 'bio'];
  const updates = {};

  for (const field of ALLOWED_FIELDS) {
    if (req.body[field] !== undefined) {
      updates[field] = req.body[field];
    }
  }

  if (Object.keys(updates).length === 0) {
    return res.status(400).json({ error: 'No valid fields provided' });
  }

  // Validate individual fields
  // isValidEmail is a simple helper: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
  if (updates.email &amp;&amp; !isValidEmail(updates.email)) {
    return res.status(400).json({ error: 'Invalid email format' });
  }

  if (updates.name &amp;&amp; (typeof updates.name !== 'string' || updates.name.length &gt; 100)) {
    return res.status(400).json({ error: 'Name must be a string of 100 characters or fewer' });
  }

  await db.query(
    'UPDATE users SET ? WHERE id = ?',
    [updates, userId]
  );

  res.json({ success: true });
});
</code></pre>
<p>For admin operations that legitimately update sensitive fields, use a separate endpoint with its own authorization:</p>
<pre><code class="language-javascript">// Admin-only endpoint for changing user roles
app.put('/api/admin/users/:id/role', authenticate, requireRole('admin'), async (req, res) =&gt; {
  if (!/^\d+$/.test(req.params.id)) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }

  const userId = Number(req.params.id);
  const { role } = req.body;

  const VALID_ROLES = ['user', 'moderator', 'admin'];

  if (!VALID_ROLES.includes(role)) {
    return res.status(400).json({ error: 'Invalid role' });
  }

  await db.query(
    'UPDATE users SET role = ? WHERE id = ?',
    [role, userId]
  );

  res.json({ success: true });
});
</code></pre>
<p><strong>Don't spread</strong> <code>req.body</code> <strong>into a database query. Build the update object field by field.</strong></p>
<h2 id="heading-3-prototype-pollution">3. Prototype Pollution</h2>
<p>Prototype pollution occurs when untrusted data is merged into an object recursively, allowing an attacker to inject properties into <code>Object.prototype</code> (the base object that every plain JavaScript object inherits from).</p>
<p>The OWASP Top 10 covers this under <a href="https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures/">Software and Data Integrity Failures (A08:2021)</a>.</p>
<h3 id="heading-how-to-identify-this-vulnerability-in-your-code">How to Identify This Vulnerability in Your Code</h3>
<p>A configuration merge utility that processes user-supplied settings:</p>
<pre><code class="language-javascript">// Vulnerable recursive merge function
function mergeConfig(target, source) {
  for (const key of Object.keys(source)) {
    if (typeof source[key] === 'object' &amp;&amp; source[key] !== null) {
      if (!target[key]) target[key] = {};
      mergeConfig(target[key], source[key]); // recursive call
    } else {
      target[key] = source[key]; // triggers __proto__ setter via bracket notation
    }
  }
}

app.post('/api/settings', authenticate, (req, res) =&gt; {
  const userSettings = {};
  mergeConfig(userSettings, req.body); // merge untrusted input
  applySettings(userSettings);
  res.json({ success: true });
});
</code></pre>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>An attacker sends this request body:</p>
<pre><code class="language-json">{
  "__proto__": {
    "isAdmin": true
  }
}
</code></pre>
<p>The recursive <code>mergeConfig</code> function reaches the <code>__proto__</code> key and executes <code>target['__proto__']['isAdmin'] = true</code>. Because <code>__proto__</code> is JavaScript's prototype accessor, this writes directly to <code>Object.prototype</code>. After the merge:</p>
<pre><code class="language-javascript">const anyObject = {};
console.log(anyObject.isAdmin); // true — inherited from Object.prototype
</code></pre>
<p>Every plain object in the running application now inherits <code>isAdmin: true</code>. If any authorization check looks like this:</p>
<pre><code class="language-javascript">if (user.isAdmin) { /* grant admin access */ }
</code></pre>
<p>That check now passes for every user, regardless of their actual role.</p>
<h3 id="heading-how-to-fix-this-vulnerability">How to Fix This Vulnerability</h3>
<p>Store user state server-side and validate each field individually. Never recursively merge untrusted input:</p>
<pre><code class="language-javascript">// Express.js - Secure
app.post('/api/settings', authenticate, async (req, res) =&gt; {
  // Load current settings from the database — never from the client
  const current = await db.query(
    'SELECT theme, language, notifications FROM user_settings WHERE user_id = ?',
    [req.user.id]
  );

  // Validate each field against an explicit allowlist
  const safeSettings = {
    theme: validateEnum(req.body.theme, ['light', 'dark'], current.theme),
    language: validateEnum(req.body.language, ['en', 'es', 'fr', 'de'], current.language),
    notifications: typeof req.body.notifications === 'boolean'
      ? req.body.notifications
      : current.notifications
  };

  await db.query(
    'UPDATE user_settings SET ? WHERE user_id = ?',
    [safeSettings, req.user.id]
  );

  res.json({ success: true });
});

function validateEnum(value, allowed, defaultValue) {
  return allowed.includes(value) ? value : defaultValue;
}
</code></pre>
<p>If you need a merge utility, use <code>Object.create(null)</code> as the base — it has no prototype, so <code>__proto__</code> can't be polluted — and allowlist keys explicitly:</p>
<pre><code class="language-javascript">// Safe merge: base object with no prototype
function safeMerge(allowedKeys, source) {
  const result = Object.create(null); // no prototype = no pollution possible

  for (const key of allowedKeys) {
    if (key in source &amp;&amp; typeof source[key] !== 'object') {
      result[key] = source[key];
    }
  }

  return result;
}
</code></pre>
<p><strong>Rules</strong>:</p>
<ul>
<li><p>Never recursively merge untrusted input into a plain object.</p>
</li>
<li><p>Store application state server-side. Don't trust clients to carry it.</p>
</li>
<li><p>Use <code>Object.create(null)</code> for data containers that will hold untrusted keys.</p>
</li>
<li><p>Validate each field by type and allowed values before using it.</p>
</li>
</ul>
<h2 id="heading-4-race-conditions">4. Race Conditions</h2>
<p>Race conditions are tricky because the code is perfectly correct. It's the timing that breaks it. Two requests arrive at almost the same moment, both check the same condition, both see a valid result, and both proceed. The result is something that should only happen once, happening twice.</p>
<p>This is called a <strong>Time-of-Check to Time-of-Use (TOCTOU)</strong> problem: the state you checked is no longer the state you're acting on.</p>
<h3 id="heading-how-to-identify-this-pattern-in-your-code">How to Identify This Pattern in Your Code</h3>
<p>A single-use coupon redemption endpoint:</p>
<pre><code class="language-javascript">// Express.js - Vulnerable
app.post('/api/redeem-coupon', authenticate, async (req, res) =&gt; {
  const { couponCode } = req.body;
  const userId = req.user.id;

  // Step 1: Check if the coupon is still valid
  const coupon = await db.query(
    'SELECT id, discount_amount, used FROM coupons WHERE code = ? AND used = false',
    [couponCode]
  );

  if (!coupon) {
    return res.status(400).json({ error: 'Invalid or already used coupon' });
  }

  // Time gap: another request can pass Step 1 here before Step 3 runs

  // Step 2: Apply the discount
  await applyDiscountToOrder(userId, coupon.discount_amount);

  // Step 3: Mark coupon as used
  await db.query(
    'UPDATE coupons SET used = true, used_by = ? WHERE code = ?',
    [userId, couponCode]
  );

  res.json({ success: true });
});
</code></pre>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p>Two requests arrive with the same coupon code at nearly the same time. Both hit Step 1 before either reaches Step 3. Both read <code>used = false</code>. Both apply the discount. One coupon, used twice.</p>
<p>The same window exists anywhere you read-then-write: balance checks before deductions, inventory checks before reservations, vote checks before incrementing. Any of them can be exploited the same way.</p>
<h3 id="heading-how-to-fix-this-vulnerability">How to Fix This Vulnerability</h3>
<p>Replace the check-then-act pattern with an atomic operation. An atomic database update guarantees that the condition check and the write happen as a single indivisible unit:</p>
<pre><code class="language-javascript">// Express.js - Secure
app.post('/api/redeem-coupon', authenticate, async (req, res) =&gt; {
  const { couponCode } = req.body;
  const userId = req.user.id;

  const connection = await db.getConnection();

  try {
    await connection.beginTransaction();

    // Atomic: only one request can update a row where used = false.
    // The database row lock ensures only one request succeeds.
    const [result] = await connection.query(
      `UPDATE coupons
       SET used = true, used_by = ?, used_at = NOW()
       WHERE code = ? AND used = false`,
      [userId, couponCode]
    );

    if (result.affectedRows === 0) {
      await connection.rollback();
      return res.status(400).json({ error: 'Invalid or already used coupon' });
    }

    const [couponRows] = await connection.query(
      'SELECT discount_amount FROM coupons WHERE code = ?',
      [couponCode]
    );
    const coupon = couponRows[0];

    await applyDiscountToOrder(userId, coupon.discount_amount, connection);

    await connection.commit();

    res.json({ success: true, discount: coupon.discount_amount });

  } catch (error) {
    await connection.rollback();
    console.error('Coupon redemption failed:', error);
    res.status(500).json({ error: 'Could not process the coupon' });
  } finally {
    connection.release();
  }
});
</code></pre>
<p>The key change is <code>UPDATE ... WHERE code = ? AND used = false</code>. The database acquires a row lock during the update. Only one concurrent request can succeed. The second request finds <code>affectedRows = 0</code> and returns an error — correctly.</p>
<p><strong>Any time you read a value to make a decision before writing — that's a potential race condition. Make the check and the write atomic.</strong></p>
<h2 id="heading-5-business-logic-flaws">5. Business Logic Flaws</h2>
<p>Business logic flaws are the hardest category to catch. Automated scanners won't find them, and code review might miss them too, because the code works exactly as written. The problem is in what the code was designed to do, not how it does it.</p>
<p>The most common form: trusting the client to send sensible numeric values.</p>
<h3 id="heading-how-to-identify-this-vulnerability-in-your-code">How to Identify This Vulnerability in Your Code</h3>
<p>An e-commerce checkout endpoint:</p>
<pre><code class="language-javascript">// Express.js - Vulnerable
app.post('/api/checkout', authenticate, async (req, res) =&gt; {
  const { items } = req.body;

  let total = 0;
  const processedItems = [];

  for (const item of items) {
    const product = await db.query(
      'SELECT id, price FROM products WHERE id = ?',
      [item.productId]
    );

    if (!product) {
      return res.status(400).json({ error: `Product not found: ${item.productId}` });
    }

    // Trust the quantity value from the client
    const itemTotal = product.price * item.quantity;
    total += itemTotal;

    processedItems.push({ productId: product.id, quantity: item.quantity, price: product.price });
  }

  if (total &gt; 100) {
    total = total * 0.9; // 10% discount
  }

  await createOrder(req.user.id, processedItems, total);
  res.json({ success: true, total });
});
</code></pre>
<h3 id="heading-why-this-matters">Why This Matters</h3>
<p><strong>Problem 1 — Negative quantity</strong>: The code multiplies the server's price by the client's quantity without checking that the quantity is positive. A user sends <code>"quantity": -5</code> on an expensive item. Its contribution to the total becomes negative, reducing the overall total.</p>
<p><strong>Problem 2 — Floating point arithmetic</strong>: <code>0.1 + 0.2</code> in JavaScript is <code>0.30000000000000004</code>. Without rounding, financial calculations accumulate errors over time.</p>
<p><strong>Problem 3 — Discount manipulation</strong>: If a separate endpoint allows modifying an order after checkout without recalculating the total, a user could add items to earn the discount, then remove items while keeping the discounted price.</p>
<h3 id="heading-how-to-fix-this-vulnerability">How to Fix This Vulnerability</h3>
<p>Validate every numeric input and recalculate all totals server-side. Use integer arithmetic (cents) for money to avoid floating point errors:</p>
<pre><code class="language-javascript">// Express.js - Secure
app.post('/api/checkout', authenticate, async (req, res) =&gt; {
  const { items } = req.body;

  if (!Array.isArray(items) || items.length === 0) {
    return res.status(400).json({ error: 'Cart must contain at least one item' });
  }

  if (items.length &gt; 50) {
    return res.status(400).json({ error: 'Cart cannot contain more than 50 items' });
  }

  let totalCents = 0; // Integer arithmetic avoids floating point errors
  const processedItems = [];

  for (const item of items) {
    if (!/^\d+$/.test(String(item.productId))) {
      return res.status(400).json({ error: `Invalid product ID: ${item.productId}` });
    }

    const productId = Number(item.productId);

    // Validate quantity: must be a string of digits only, between 1 and 10
    // parseInt("3abc", 10) returns 3 — we use regex to prevent this
    if (!/^\d+$/.test(String(item.quantity))) {
      return res.status(400).json({
        error: `Invalid quantity for product ${productId}`
      });
    }

    const quantity = Number(item.quantity);

    if (quantity &lt; 1 || quantity &gt; 10) {
      return res.status(400).json({
        error: `Quantity for product ${productId} must be between 1 and 10`
      });
    }

    const product = await db.query(
      'SELECT id, name, price_cents, stock FROM products WHERE id = ? AND active = true',
      [productId]
    );

    if (!product) {
      return res.status(400).json({ error: `Product not found: ${productId}` });
    }

    if (product.stock &lt; quantity) {
      return res.status(400).json({
        error: `Insufficient stock for "${product.name}"`
      });
    }

    // Use the server's price — never trust a price from the client
    totalCents += product.price_cents * quantity;

    processedItems.push({
      productId: product.id,
      name: product.name,
      quantity,
      unitPriceCents: product.price_cents
    });
  }

  // Integer arithmetic for the discount calculation
  const discountMultiplier = totalCents &gt; 10000 ? 90 : 100; // 10000 cents = $100
  const finalTotalCents = Math.round(totalCents * discountMultiplier / 100);

  await createOrder(req.user.id, processedItems, finalTotalCents);

  res.json({
    success: true,
    total: (finalTotalCents / 100).toFixed(2),
    currency: 'USD'
  });
});
</code></pre>
<p>What changed and why:</p>
<ul>
<li><p>Integer (cents) arithmetic eliminates floating point errors. <code>10000 + 3000</code> in integer cents is always exact.</p>
</li>
<li><p><code>quantity &lt; 1 || quantity &gt; 10</code> prevents negative quantities and unreasonably large orders.</p>
</li>
<li><p><code>items.length &gt; 50</code> prevents oversized requests.</p>
</li>
<li><p><code>product.stock &lt; quantity</code> ensures the order doesn't exceed available inventory.</p>
</li>
<li><p>All totals, discounts, and final prices are calculated server-side from server-side prices.</p>
</li>
</ul>
<p><strong>Define the valid range for every numeric input. Recalculate every total server-side. The client isn't a trusted source for prices or quantities.</strong></p>
<h2 id="heading-6-jwt-misconfiguration">6. JWT Misconfiguration</h2>
<p>JWTs are everywhere in Node.js APIs, and the <code>jsonwebtoken</code> library makes them easy to use. That's both good and bad: they're easy to use correctly, but they're also easy to use in ways that look fine until they're not.</p>
<p>The OWASP Top 10 classifies authentication failures under <a href="https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/">Identification and Authentication Failures (A07:2021)</a>. Three misconfigurations show up repeatedly.</p>
<h3 id="heading-how-to-identify-this-vulnerability-in-your-code">How to Identify This Vulnerability in Your Code</h3>
<p><strong>Mistake 1 — Algorithm not specified in</strong> <code>verify()</code>:</p>
<pre><code class="language-javascript">// Vulnerable
const decoded = jwt.verify(token, process.env.JWT_SECRET);
</code></pre>
<p>Without an <code>algorithms</code> option, some JWT implementations can be tricked into accepting tokens that declare <code>"alg": "none"</code> in their header — meaning no signature is required at all.</p>
<p><strong>Mistake 2 — Weak or hardcoded secrets</strong>:</p>
<pre><code class="language-javascript">// Vulnerable
const token = jwt.sign({ userId: user.id }, 'secret');
</code></pre>
<p>A short or predictable HS256 secret can be brute-forced offline if an attacker obtains a valid token.</p>
<p><strong>Mistake 3 — Sensitive data in the payload</strong>:</p>
<pre><code class="language-javascript">// Vulnerable
const token = jwt.sign({
  userId: user.id,
  passwordHash: user.passwordHash, // never do this
  role: user.role
}, secret);
</code></pre>
<p>JWT payloads are base64-encoded, not encrypted. Anyone who holds the token can decode the payload and read its contents.</p>
<h3 id="heading-how-to-fix-these-issues">How to Fix These Issues</h3>
<pre><code class="language-javascript">// Secure JWT implementation
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

// Generate a strong secret once and store it as an environment variable:
// node -e "console.log(crypto.randomBytes(64).toString('hex'))"
const JWT_SECRET = process.env.JWT_SECRET;

if (!JWT_SECRET || Buffer.from(JWT_SECRET, 'hex').length &lt; 32) {
  throw new Error('JWT_SECRET must be at least 32 random bytes');
}

function signToken(userId) {
  return jwt.sign(
    { sub: userId },         // 'sub' is the standard claim for the user identifier
    JWT_SECRET,
    {
      algorithm: 'HS256',    // always declare the algorithm explicitly
      expiresIn: '15m',      // short-lived tokens reduce the window if a token is stolen
      issuer: 'your-app-name',
      audience: 'your-app-name'
    }
  );
}

function verifyToken(token) {
  return jwt.verify(token, JWT_SECRET, {
    algorithms: ['HS256'],   // whitelist only the expected algorithm
    issuer: 'your-app-name',
    audience: 'your-app-name'
  });
}

function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  const token = authHeader.split(' ')[1];

  try {
    const decoded = verifyToken(token);
    req.user = { id: decoded.sub };
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}
</code></pre>
<p><strong>A note on token revocation</strong>: JWTs are stateless, meaning your server keeps no record of them. This means you can't immediately invalidate a token on logout or account compromise without extra infrastructure.</p>
<p>Common solutions include short-lived access tokens (15 minutes) paired with refresh tokens stored server-side, or a token denylist in a fast store like Redis. Choose the approach that matches your application's requirements.</p>
<p><strong>JWT security checklist</strong>:</p>
<ul>
<li><p>Always pass <code>algorithms: ['HS256']</code> to <code>verify()</code>.</p>
</li>
<li><p>Use a secret of at least 32 random bytes generated with <code>crypto.randomBytes</code>.</p>
</li>
<li><p>Set short expiration times.</p>
</li>
<li><p>Store only non-sensitive identifiers (user ID) in the payload — not emails, passwords, or roles.</p>
</li>
<li><p>Use standard claims: <code>sub</code>, <code>iss</code>, <code>aud</code>, <code>exp</code>.</p>
</li>
<li><p>Plan your revocation strategy before going to production.</p>
</li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>Here's a quick reference for the six vulnerability categories covered in this tutorial:</p>
<table>
<thead>
<tr>
<th>Vulnerability</th>
<th>Root Cause</th>
<th>Core Fix</th>
</tr>
</thead>
<tbody><tr>
<td>IDOR</td>
<td>Authorization check missing</td>
<td>Verify ownership from the authenticated session</td>
</tr>
<tr>
<td>Mass Assignment</td>
<td>All request body fields applied to database</td>
<td>Allowlist allowed fields explicitly</td>
</tr>
<tr>
<td>Prototype Pollution</td>
<td>Recursive merge of untrusted input</td>
<td>Store state server-side. Use <code>Object.create(null)</code> for merge targets.</td>
</tr>
<tr>
<td>Race Condition</td>
<td>Check-then-act without atomicity</td>
<td>Atomic <code>UPDATE ... WHERE condition</code> or transactions</td>
</tr>
<tr>
<td>Business Logic Flaw</td>
<td>Trusting client-supplied numeric values</td>
<td>Regex-validate inputs. Use integer arithmetic for money.</td>
</tr>
<tr>
<td>JWT Misconfiguration</td>
<td>No algorithm allowlist, weak secrets</td>
<td>Explicit algorithm array, strong random secret, short expiration</td>
</tr>
</tbody></table>
<p>None of these vulnerabilities requires a clever attacker. They just need code that trusts the wrong thing at the wrong time.</p>
<p>The patterns worth internalizing: always derive authorization from the session, never from the request. Validate every numeric input with a range. Make financial writes atomic. Build your JWT configuration explicitly.</p>
<p>Understanding how to fix these vulnerabilities is one side of the picture. Understanding how they're actually identified and exploited during a real security assessment is the other.</p>
<p>If you want to go deeper on the offensive side — how penetration testers approach web application targets, what they look for, and how they chain multiple flaws together — this <a href="https://hackita.it/articoli/attacchi-applicazioni-web/">guide to web application attack techniques</a> covers that perspective in detail.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
