post到django API在被认证时返回403 (Forbidden),但在未被认证时返回able post.<



我正在构建一个应用程序,工作原理如下:

  • 用户在html表单上填写数据并提交。
  • 数据被发布到API(通过Fetch)。

这个应用程序使用django, django rest框架工作与纯html和香草java我的问题是,当用户在API/后端上进行身份验证时,我无法发布。它返回403。但是,当我没有经过身份验证时,我可以从表单中发布数据。

下面是form.html中向API发送数据的JS:

<script>
console.log('js linked')
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken)
function post_report(event) {
event.preventDefault();
var contact_email = document.getElementById("contact_email").value
var contact_number = document.getElementById("contact_number").value
var date_time = document.getElementById("date_time").value
var location = document.getElementById("location").value
var description = document.getElementById("description").value
console.log(contact_email + ' ' + description)

fetch("http://127.0.0.1:8000/api/Flight_Safety_Reports/",{
method: "POST",
mode: 'same-origin',
headers:{
"Accept": "application/json",
'Content-Type':'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify({
contact_email:contact_email,
contact_number:contact_number,
date_time:date_time,
location:location,
description:description
})
})
.then(response =>console.log(response))
alert('report submitted')
}
</script>

views.py

from app_reports.models import (
FlightSafetyReport
)
from .serializers import (
FlightSafetyReportSerializer
)
class FlightSafetyReportViewSet(viewsets.ModelViewSet):
serializer_class = FlightSafetyReportSerializer
queryset = FlightSafetyReport.objects.all()

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'bootstrap4',
'rest_framework',
'corsheaders',
'articles',
'user_api',
'app_sandbox',

'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth',
'rest_auth.registration',
'rest_framework.authtoken',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'djreact.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BUILD_DIR, BACKEND_TEMPLATES_DIR],
'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 = 'djreact.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
CORS_ORIGIN_ALLOW_ALL = True

STATICFILES_DIRS = [os.path.join(BUILD_DIR,'static')]

CSRF_COOKIE_NAME = "XSRF-TOKEN"

重申一下,当我没有登录到api/当我没有登录到django-admin时,我可以发布。当我登录时,我得到一个403禁止错误。

我认为你的请求是这样的。问题可能是您传递了一个无效的csrftoken。我已经在我这边创建了你的代码的副本,它工作。它开始给我403错误,当我改变csrftoken值为一些随机值。就像下面的一样。

var csrftoken = getCookie('csrftoken');
csrftoken = "blacjcjsjsjss";

然后在控制台中给出403 Forbidden错误。如果我去掉csrftoken = "blacjcjsjsjss";,它又开始工作了。我要说的是,你的csrftoken值是错误的。您需要确保您获得的是正确的加密令牌。

相关内容

  • 没有找到相关文章

最新更新