HIGH jwt misconfigurationdjangobearer tokens

Jwt Misconfiguration in Django with Bearer Tokens

Jwt Misconfiguration in Django with Bearer Tokens — how this specific combination creates or exposes the vulnerability

JWT misconfiguration in Django when using Bearer Tokens commonly arises from missing or incorrect validation of token signatures, algorithms, audiences, and issuers. In this setup, an API endpoint expects an Authorization header formatted as Bearer <token>. If the backend decodes the token without verifying its cryptographic signature, it may trust any payload, enabling identity spoofing.

Another common issue is accepting unsigned tokens (alg=none) or overly permissive algorithm lists (e.g., accepting both HS256 and RS256 without strict checks). When the secret or public key is weak, leaked, or incorrectly loaded, attackers can forge tokens. Additionally, failing to validate standard claims such as exp (expiration), nbf (not before), and aud (audience) leads to replay attacks or the acceptance of tokens intended for other services. Without proper scope or role checks, privilege escalation or broken object level authorization (BOLA/IDOR) can occur when a token with elevated permissions is reused across endpoints.

Middleware and view logic that parses the Authorization header manually are prone to mistakes. For example, extracting the token with a simple string split and passing it directly to a decoder without handling malformed headers gracefully can expose stack traces or leak timing information. If token revocation is not implemented (e.g., via denylist or short-lived tokens with refresh mechanisms), compromised tokens remain valid beyond their intended lifespan.

These risks are magnified when token validation is inconsistent across endpoints or when optional authentication is used without clear boundaries. A misconfigured CORS policy combined with Bearer Token usage can also expose tokens to unauthorized JavaScript origins. In secure API designs, each endpoint that requires authentication must validate the token’s signature, claims, and scopes, enforce HTTPS, and reject tokens that do not meet strict criteria.

Regular automated scans, such as those provided by middleBrick, help detect JWT misconfigurations by inspecting the unauthenticated attack surface and identifying missing validation controls. These scans complement runtime testing and should be integrated into CI/CD pipelines using the middleBrick GitHub Action to fail builds when risky patterns are detected before deployment.

Bearer Tokens-Specific Remediation in Django — concrete code fixes

To remediate JWT misconfiguration with Bearer Tokens in Django, enforce strict token validation using a well-maintained library such as PyJWT. Always specify the expected algorithm and validate standard claims. Below is a secure example that decodes and verifies a Bearer Token in a Django view.

import jwt
from django.conf import settings
from django.http import JsonResponse
from django.views import View

class ProtectedView(View):
    def get(self, request):
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({'error': 'Unauthorized'}, status=401)

        token = auth_header.split(' ')[1]
        try:
            decoded = jwt.decode(
                token,
                settings.SECRET_KEY if settings.JWT_ALGORITHM == 'HS256' else settings.JWT_PUBLIC_KEY,
                algorithms=[settings.JWT_ALGORITHM],
                options={
                    'verify_signature': True,
                    'require_exp': True,
                    'require_nbf': True,
                    'require_iat': True,
                },
                audience=settings.JWT_AUDIENCE,
                issuer=settings.JWT_ISSUER,
            )
            # Use decoded claims for authorization, e.g., check scopes or roles
            return JsonResponse({'message': 'Access granted', 'user': decoded.get('sub')})
        except jwt.ExpiredSignatureError:
            return JsonResponse({'error': 'Token expired'}, status=401)
        except jwt.InvalidTokenError:
            return JsonResponse({'error': 'Invalid token'}, status=401)

Ensure that settings.JWT_ALGORITHM is set to a strong algorithm such as RS256, and that settings.JWT_PUBLIC_KEY contains the correct public key in PEM format. For symmetric keys, use a high-entropy SECRET_KEY and rotate it periodically. Always serve requests over HTTPS to prevent token interception.

In addition to view-level validation, apply checks at the middleware layer to reject malformed or unsigned tokens early. Avoid accepting tokens with alg=none and explicitly define a denylist for revoked tokens, checking it within the validation flow. Combine these measures with short token lifetimes and refresh token rotation to reduce the impact of token leakage.

When using third-party identity providers, validate the issuer and audience strictly and map claims to user permissions securely. The middleBrick CLI can be used locally with middlebrick scan <url> to verify that your endpoints enforce these controls, while the middleBrick MCP Server allows you to scan APIs directly from your AI coding assistant during development.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

What should I do if my Django API accepts unsigned JWTs?
Reject unsigned tokens by setting algorithms to a signed option (e.g., RS256 or HS256) and never accept 'none' in the algorithm list. Validate the signature on every request and enforce strict claims checks.
How can I prevent Bearer Token leakage in browser-based JavaScript?
Avoid storing Bearer Tokens in local storage; use httpOnly cookies with Secure and SameSite attributes for session management, or ensure tokens are only handled in memory for SPAs with strict CORS policies and short expiration times.