0

I am trying to login to my back-end written in django-rest-framework from my frontend written in Angular 7. Whenever I tries to login, I gets an error

Access to XMLHttpRequest at 'http://localhost:8000/api-auth/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

When I tried the same API from postman, I got another error -

CSRF verification failed. Request aborted.

I am not sure how to include csrf token in my app to resolve this error.

my login.html

 <form [formGroup]="loginForm" (ngSubmit)="login()">
              <div class="row">
                <div class="col-md-12 align-content-center py-3">
                  <mat-form-field>
                    <input matInput placeholder="Enter your username" formControlName="loginUsername">
                  </mat-form-field>
                </div>
                <div class="col-md-12 align-content-center py-3">
                  <mat-form-field>
                    <input matInput placeholder="Enter your password" type="password" formControlName="loginPassword">
                  </mat-form-field>
                </div>
                <div class="col-md-12 align-content-center py-3">
                  <button mat-raised-button type="submit">Login</button>
                </div>
              </div>
            </form>

and login.serivce file is as follows:

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';

export interface Login {
  username: string;
  password: string;
}

export interface Signup {
  username: string;
  email: string;
  password: string;
}


@Injectable()
export class LoginSignUpService {

  loginObject: Login;
  signupObject: Signup;

  constructor(private http: HttpClient) {
  }

  public login(username: string, password: string) {

    this.loginObject = {
      username, password
    };
    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Access-Control-Allow-Headers', 'Content-Type');
    headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');

    const options = {headers};

    return this.http.post('http://localhost:8000/api-auth/login', this.loginObject, options);
  }
}

On my server side, my settings.py file is as follows:

"""
Django settings for atest_blog project.

Generated by 'django-admin startproject' using Django 2.1.7.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ct9jv$%i%h336p40#)bus7!eu2$@%e%o#w47*&ltccl%@#(z$q'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'atest.apps.AtestConfig',
    'rest_framework',
    'rest_framework.authtoken',
    'comments.apps.CommentsConfig',
    'corsheaders'
]

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

ROOT_URLCONF = 'atest_blog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'atest_blog.wsgi.application'

# REST_FRAMEWORK = {
#     'DEFAULT_AUTHENTICATION_CLASSES': (
#         'rest_framework.authentication.TokenAuthentication',
#     ),
#     'DEFAULT_PERMISSION_CLASSES': (
#         'atest.permissions.IsOwnerOrReadOnly',
#     ),
# }

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': '*******************',
        'NAME': '***************',
        'USER': '***************',
        'PASSWORD': '**************************',
        'HOST': '**************************',
        'PORT': '',
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

CORS_ORIGIN_ALLOW_ALL = True

# CORS_ORIGIN_WHITELIST = (
#     'http//:localhost:4200',
# )

I have also added corsheaders in my server as I was facing the CORS issue earlier and it resolved my issue for CORS for other page.

Please help me resolving this.

VIBHOR GOYAL
  • 473
  • 1
  • 6
  • 22

1 Answers1

1

You need to enable CORS and disable the Adblocker :) CORS allows client applications to interface with APIs hosted on different domains by enabling modern web browsers to bypass the Same origin Policy which is enforced by default. Install the library provided:

INSTALLED_APPS = (
...
'corsheaders',
...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]

For complete configuration please see the documentation.

Mirza715
  • 420
  • 5
  • 15