Форум сайта python.su
Всем привет!
Столкнулся с проблемой что джанга не может проверить csrf запроса. И постоянно выдает 403 ошибки. Т.к. куки до этого не чистились то я даже не могу сказать после чего перестало работать.
Само приложении делаю в связке Django + Angular.
Код ангуляра такой:
var app = angular.module('app', ['ngRoute', 'ngCookies']); app.config(function($interpolateProvider) { $interpolateProvider.startSymbol('{$'); $interpolateProvider.endSymbol('$}'); }); app.config(['$httpProvider', function($httpProvider) { // $httpProvider.defaults.xsrfCookieName = 'csrftoken'; // $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }]); app.run(function($http, $cookies) { $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken; }) app.config(function($routeProvider) { $routeProvider.when('/', { templateUrl: 'static/templates/main.html' , controller: 'MainController' }); $routeProvider.when('/reg/', { templateUrl: 'static/templates/reg.html', controller: 'RegFormController' }); $routeProvider.when('/login/', { templateUrl: 'static/templates/login.html', controller: 'LoginFormController' }); $routeProvider.when('/add/', { templateUrl: 'static/templates/add.html', controller: 'CreateFormController' }); $routeProvider.when('/logout/', { // templateUrl: 'static/templates/login.html', controller: 'LogoutController' }); $routeProvider.otherwise({redirectTo: '/'}); }); app.controller('LoginFormController', ['$scope', '$http', '$location', '$cookies', function($scope, $http, $location, $cookies) { $scope.submit = function() { var in_data = {login: $scope.login}; var req = { method: 'POST', url: '/login/', headers: { "x-csrftoken" : $cookies.csrftoken }, data: in_data, } // $http.post('/login/', angular.toJson(in_data)) $http(req) .success(function(data, status) { console.log(data + status); $location.path("/main"); }) .error(function(data, status) { console.log(data + status); }); }; }]);
<h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> ... <p>Reason given for failure:</p> <pre> CSRF cookie not set. </pre>
Офлайн
а перестало работать после того как вы закомментировали?
// $httpProvider.defaults.xsrfCookieName = 'csrftoken'; // $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
Отредактировано inoks (Март 4, 2015 11:31:36)
Офлайн
Закомментировал я уже после того как это все обнаружил и пытался как-то исправить. Так что если все это раскомментировать то моя проблема не исчезнет
Офлайн
Стоит попробовать “задекорировать” view на которое Django возвращает эту ошибку
@csrf_exempt
Офлайн
class Login(View): @csrf_exempt def post(self, request, *args, **kwargs): in_data = json.loads(request.body) form = forms.Login(in_data['login']) if form.is_valid(): if form.get_user(): login(request, form.get_user()) return HttpResponse() else: return HttpResponse('Login Error', status='403') else: return HttpResponse('Login Error', status='403')
Офлайн
Для class based view декорирование по другому делается:
https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-class-based-views
И в куках у меня ничего не создаетсяСтранно, а должно по-идее быть: https://docs.djangoproject.com/en/dev/ref/csrf/
Офлайн
После того как прописал декоратор код отработал.
Но в куках все равно нет ключа “csrftoken”. При том что они не отключены. Для сайта в куках или просто в локальных данных лежит “Индексированная база данных”.
Settings.py
""" Django settings for finance_v2 project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'zq&q-fpo=o)v%&qup(=fm!1rut00y7cvskv*0$2yegn1nml404' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_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', 'finance_v2', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'finance_v2.urls' WSGI_APPLICATION = 'finance_v2.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/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/1.7/howto/static-files/ STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'static/templates'), )
Отредактировано balalay12 (Март 4, 2015 18:15:30)
Офлайн
И постоянно выдает 403 ошибкиА что это за view?) Это тестовое или реальное? Может причина в самом view?)return HttpResponse('Login Error', status='403')
Офлайн
<div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF cookie not set. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function uses <a href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext'><code>RequestContext</code></a> for the template, instead of <code>Context</code>.</li> <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> </ul> <p>You're seeing the help section of this page because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and only the initial error message will be displayed. </p> <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> </div> </body> </html> 403"
Отредактировано balalay12 (Март 4, 2015 18:50:35)
Офлайн
Так а в браузере кука ставится?
Если открыть статичную страницу с {%csrf_token %} в браузере кука появляется? Желательно в нескольких проверить.
В админку вы нормально логинетесь?
Офлайн