来自 Chrome 扩展的获取请求结果为 403 Forbidden
Fetch request from Chrome extension results in 403 Forbidden
每当我尝试从我的 Chrome 扩展程序的 background.js
发送 POST 请求时,我都会收到 403 Forbidden
错误。如果我在 Chrome 扩展之外执行相同的代码,它会正常工作。我的 API 不需要任何身份验证。
请求代码:
let formData = new FormData();
formData.append('message', "This is a test message.");
fetch('https://myapi.com/add', {
body: formData,
method: "post"
}).then(r => console.log(r));
请求响应:
我还检查了我的 Apache 2 access.log
,一切看起来都很正常:
x.x.x.x - - [13/Sep/2020:17:02:30 +0000] "POST add HTTP/1.1" 403 581 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"
是否有任何 Chrome 扩展政策可以阻止我的请求?
我需要向我的 manifest.json
添加任何特殊权限吗?
我是否需要对我的 API 进行任何更改(将其作为保留,因为它在 Chrome 扩展之外正常工作)?
Edit: Read your server logs. The server is probably telling you exactly what the error is. Make sure debugging is enabled.
403 错误并不是真正从服务器发出的,没有充分的理由 - 这个原因通常特定于您的应用程序。 403 通常是权限问题:我们知道你是谁,但你无权做你想做的事。
可能存在(或缺失)header 阻止请求进行任何更改(在您的情况下,POST 请求)。例如,您的服务器可能正在设置 cookie 以防止 CSRF 攻击。很多时候服务器不会验证 GET 请求的令牌,这可以解释为什么 GET 请求适用于您的情况而不是 POST 请求。
如果你能搜索到你的服务器代码,我愿意有这样的伪代码:
if (requestIsMissingCSRFToken()) {
throw new Error(STATUS.FORBIDDEN)
}
编辑:一些相关链接
问题出在 Django REST 框架中。显然它默认启用了一些身份验证类。 Disabling/setting 它们在 settings.py
中的空数组将摆脱烦人的“403 Forbidden”错误。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
]
}
编辑:我不知道这有多安全,但至少它有效。
我刚刚遇到了同样的问题。非常感谢您发布此信息。我还在使用 Django 后端开发 Chrome 扩展。
我从 'DEFAULT_AUTHENTICATION_CLASSES' 中删除了 'rest_framework.authentication.SessionAuthentication',但我保留了 'oauth2_provider.contrib.rest_framework.OAuth2Authentication'。
根据这个 medium article “rest_framework.authenication.SessionAuthentication' 仅当您想要保持可浏览时才需要 API。我启用了 CSRF 和 CORS。所以我认为我的设置非常安全.
下面是我的 settings.py 文件。
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*xbmoy2yt4%l=od-dm*w$dxpl+rb(n#rmv0n&0x$a@+io!j+++'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'audio.apps.AudioConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'rest_framework',
'oauth2_provider',
#'corsheaders',
]
MIDDLEWARE = [
#'corsheaders.middleware.CorsMiddleware',
'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',
'oauth2_provider.middleware.OAuth2TokenMiddleware'
]
ROOT_URLCONF = 'zeno.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 = 'zeno.wsgi.application'
CORS_ORIGIN_ALLOW_ALL = True
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CORS_ORIGIN_ALLOW_ALL = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, '..', 'static'),
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
#'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
# 'DEFAULT_PAGINATION_CLASS': (
# 'rest_framework.pagination.PageNumberPagination',
# ),
# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
# ),
#'PAGE_SIZE': 10
}
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # To keep the Browsable API
'oauth2_provider.backends.OAuth2Backend',
)
#STATIC_ROOT = os.path.join(BASE_DIR, "static/")
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'test.com']
AUTH_USER_MODEL = 'accounts.CustomUser'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
#EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails")
每当我尝试从我的 Chrome 扩展程序的 background.js
发送 POST 请求时,我都会收到 403 Forbidden
错误。如果我在 Chrome 扩展之外执行相同的代码,它会正常工作。我的 API 不需要任何身份验证。
请求代码:
let formData = new FormData();
formData.append('message', "This is a test message.");
fetch('https://myapi.com/add', {
body: formData,
method: "post"
}).then(r => console.log(r));
请求响应:
我还检查了我的 Apache 2 access.log
,一切看起来都很正常:
x.x.x.x - - [13/Sep/2020:17:02:30 +0000] "POST add HTTP/1.1" 403 581 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"
是否有任何 Chrome 扩展政策可以阻止我的请求?
我需要向我的 manifest.json
添加任何特殊权限吗?
我是否需要对我的 API 进行任何更改(将其作为保留,因为它在 Chrome 扩展之外正常工作)?
Edit: Read your server logs. The server is probably telling you exactly what the error is. Make sure debugging is enabled.
403 错误并不是真正从服务器发出的,没有充分的理由 - 这个原因通常特定于您的应用程序。 403 通常是权限问题:我们知道你是谁,但你无权做你想做的事。
可能存在(或缺失)header 阻止请求进行任何更改(在您的情况下,POST 请求)。例如,您的服务器可能正在设置 cookie 以防止 CSRF 攻击。很多时候服务器不会验证 GET 请求的令牌,这可以解释为什么 GET 请求适用于您的情况而不是 POST 请求。
如果你能搜索到你的服务器代码,我愿意有这样的伪代码:
if (requestIsMissingCSRFToken()) {
throw new Error(STATUS.FORBIDDEN)
}
编辑:一些相关链接
问题出在 Django REST 框架中。显然它默认启用了一些身份验证类。 Disabling/setting 它们在 settings.py
中的空数组将摆脱烦人的“403 Forbidden”错误。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
]
}
编辑:我不知道这有多安全,但至少它有效。
我刚刚遇到了同样的问题。非常感谢您发布此信息。我还在使用 Django 后端开发 Chrome 扩展。
我从 'DEFAULT_AUTHENTICATION_CLASSES' 中删除了 'rest_framework.authentication.SessionAuthentication',但我保留了 'oauth2_provider.contrib.rest_framework.OAuth2Authentication'。
根据这个 medium article “rest_framework.authenication.SessionAuthentication' 仅当您想要保持可浏览时才需要 API。我启用了 CSRF 和 CORS。所以我认为我的设置非常安全.
下面是我的 settings.py 文件。
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*xbmoy2yt4%l=od-dm*w$dxpl+rb(n#rmv0n&0x$a@+io!j+++'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'audio.apps.AudioConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'rest_framework',
'oauth2_provider',
#'corsheaders',
]
MIDDLEWARE = [
#'corsheaders.middleware.CorsMiddleware',
'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',
'oauth2_provider.middleware.OAuth2TokenMiddleware'
]
ROOT_URLCONF = 'zeno.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 = 'zeno.wsgi.application'
CORS_ORIGIN_ALLOW_ALL = True
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CORS_ORIGIN_ALLOW_ALL = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, '..', 'static'),
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
#'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
# 'DEFAULT_PAGINATION_CLASS': (
# 'rest_framework.pagination.PageNumberPagination',
# ),
# 'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
# ),
#'PAGE_SIZE': 10
}
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # To keep the Browsable API
'oauth2_provider.backends.OAuth2Backend',
)
#STATIC_ROOT = os.path.join(BASE_DIR, "static/")
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'test.com']
AUTH_USER_MODEL = 'accounts.CustomUser'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
#EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend"
#EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_emails")