将Django部署到DigitalOcean时反应axios CSRF 403 FORBIDDEN

时间:2018-12-07 06:27:15

标签: django reactjs axios

以下动作创建者设置在本地运行良好。但是,当在DigitalOcean中部署站点时,我会不断收到CSRF 403 FORBIDDEN,因此无法验证用户身份。

错误-> POST https://app-machinespector.com/auth/signin/ 403(禁止)

动作创建者,用于验证用户身份。我正在加载cookie,但没有在任何地方使用它(因为它没有必要)。它的值为 undefined ...

import axios from 'axios';
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

import { browserHistory } from 'react-router';
import cookie from 'react-cookie';


import {
  AUTH_USER,
} from './types';

# load and print cookie --> undefined
const csrftoken =  cookie.load('csrftoken');
console.log(csrftoken);

export function signinUser({email, password}){
  return function(dispatch){
    axios.post('/auth/signin/', { email, password })
      .then(response => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/machines');
      })
      .catch(() =>{
        dispatch(authError('Log in credentials are invalid'));
      });
  }
}

Django生产设置

from .base import *  # noqa

DEBUG = False

# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
SECRET_KEY = env('DJANGO_SECRET_KEY')

# ALLOWED_HOSTS
# ------------------------------------------------------------------------------
ALLOWED_HOSTS=["app-machinespector.com", "localhost", "127.0.0.1"]

# CSRF
# -------------------------------------------------
CSRF_USE_SESSIONS = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_NAME  = 'csrftoken'
CSRF_HEADER_NAME  = 'X-CSRFToken'

# WEBPACK CONFIGURATION
# ------------------------------------------------------------------------------
WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/prod/',  # end with slash
        'STATS_FILE': str(ROOT_DIR.path('webpack-stats-prod.json')),
    }
}

Nginx https服务器配置

upstream app_server {
    server  django:8000 fail_timeout=0;
}

server {

    listen  443 ssl;
    server_name  app-machinespector.com www.app-machinespector.com;

    ssl_certificate  /etc/letsencrypt/live/app-machinespector.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/app-machinespector.com/privkey.pem;


    location /static/ {
        autoindex off;
        alias /var/www/static/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }

}

server {

   listen  80;
   server_name  app-machinespector.com;

   return 301  https://$host$request_uri;

}

0 个答案:

没有答案