由于Angular-Django中的CSRF错误而无法登录

问题描述 投票:0回答:1

我试图从我在Angular 7中编写的前端登录到django-rest-framework中编写的后端。每当我尝试登录时,我都会收到错误

从'http://localhost:8000/api-auth/login'访问'http://localhost:4200'的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

当我从邮递员那里尝试相同的API时,我又遇到了另一个错误 -

CSRF验证失败。请求中止。

我不知道如何在我的应用程序中包含csrf令牌来解决此错误。

我的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>

和login.service文件如下:

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);
  }
}

在我的服务器端,我的settings.py文件如下:

"""
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',
# )

我之前在服务器中添加了corsheaders,因为我之前遇到了CORS问题,它为其他页面解决了我的CORS问题。

请帮我解决这个问题。

django angular django-rest-framework angular-http django-csrf
1个回答
1
投票

您需要启用CORS并禁用Adblocker :) CORS允许客户端应用程序与托管在不同域上的API连接,方法是使现代Web浏览器绕过默认强制执行的同源策略。安装提供的库:

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

您还需要添加一个中间件类来监听响应:

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

有关完整配置,请参阅documentation

© www.soinside.com 2019 - 2024. All rights reserved.