CORS_ALLOWED_ORIGINS is allowing every localhost port

So letme just explain what i’m doing:

I’ve made a Django REST API for To-do App! Runnig on http://127.0.0.1:5690/

Then i’ve made a frontend for To-do App, Using Django Template in another Django Project! Running on http://127.0.0.1:9998/

Lets understand what i’m trying to achieve:

I want that only the django http://127.0.0.1:8000/ can access the API Service

What is did to achieve this goal?

  1. Implemented Token authentication using JWT.
  2. Used django-cors-headers

What the PROBLEM is?

The CORS_ALLOWED_ORIGINS is allowing all the ports to request and get response from the api. And Not restricting the access just to http://127.0.0.1:8000/.

I have already tried multiple AI tools for the answer and nothing works.
I have already tried clearing cache, changing port for both for frontend and api service!
I have already shutdown/restarted my system multiple times.

My API Code:

DjangoProject name: todoAppBackendApi
DjangoApp name: taskManagement

manage.py: (Added this to set default port)

from django.core.management.commands.runserver import Command as runserver
runserver.default_port = "5690"

todoAppBackendApi/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'taskManagement',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1:8000",  
]

todoAppBackendApi/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('taskManagement.urls')),
]

taskManagement/urls.py:

router = DefaultRouter()
router.register('tasks', views.TaskViewSet, basename='tasks')

urlpatterns = [
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('', include(router.urls)),
]

taskManagement/views.py:

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

Terminal Logs:

(rest) A:\Language\Python\Django\Projects\My Project\to-do\todoAppBackendApi>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 01, 2023 - 15:03:16
Django version 4.2.1, using settings 'todoAppBackendApi.settings'
Starting development server at http://127.0.0.1:5690/
Quit the server with CTRL-BREAK.

[01/Jun/2023 15:04:50] "POST /api/token/ HTTP/1.1" 200 483
[01/Jun/2023 15:04:50] "GET /api/tasks/ HTTP/1.1" 200 895

My Frontend Django Code:

DjangoProject name: todo
DjangoApp name: frontend

frontend/urls.py:

urlpatterns = [
    path('', views.index, name='index'),
]

frontend/views.py:

def index(request):
    # Obtain the token
    response = requests.post('http://127.0.0.1:5690/api/token/', data={'username': 'todoApp', 'password': '27112002-Ankit'})
    
    if response.status_code == 200:
        # Extract the token from the response
        token = response.json().get('access')
        
        # Include the token in the request headers
        headers = {
            'Authorization': f'Bearer {token}',
        }
        
        # Make API requests with the headers
        api_response = requests.get('http://127.0.0.1:5690/api/tasks/', headers=headers).json()
        
        return render(request, 'index.html', {'response': api_response})
    else:
        # Handle authentication error
        return render(request, 'index.html', {'response': 'Authentication failed'})

Terminal Logs:

(rest) A:\Language\Python\Django\Projects\My Project\to-do\todoApp>python manage.py runserver 9998
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 01, 2023 - 15:01:58
Django version 4.2.1, using settings 'todoApp.settings'
Starting development server at http://127.0.0.1:9998/
Quit the server with CTRL-BREAK.

[01/Jun/2023 15:02:03] "GET / HTTP/1.1" 200 4623

Request Header:

GET / HTTP/1.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: 127.0.0.1:9998
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36
sec-ch-ua: "Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"

Response Header:

HTTP/1.1 200 OK
Date: Thu, 01 Jun 2023 09:32:03 GMT
Server: WSGIServer/0.2 CPython/3.11.0
Content-Type: text/html; charset=utf-8
X-Frame-Options: DENY
Content-Length: 4623
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin

That’s correct. I think there’s a little bit of a misunderstanding of what CORS is or does here.

CORS is a security feature involving a browser that has retrieved JavaScript code from one site, and that JavaScript code is making a request to a different site. See Cross-Origin Resource Sharing (CORS) - HTTP | MDN

It doesn’t apply in this situation.