我使用python和urllib模块来POST我登录通用django视图的凭证,仅此而已。我尝试了一些基于标准基本身份验证模式的东西,修改认证头....但是同样的,它总是给我一个403禁止代码.我寻找一个解决这个问题的答案,但对我来说....我找不到。
from django.contrib.auth import views
urlpatterns = [
path('accounts/login/', views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]
settings.py
"""
Django settings for tests project.
Generated by 'django-admin startproject' using Django 2.2.17.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ukqp@#s^bo)wcl)qr#fc1%+-1rm(f1-6(8trin3rl)6=dbwt@9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
LOGIN_REDIRECT_URL = '/catalog/'
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog.apps.CatalogConfig',
'accounts.apps.AccountsConfig',
]
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',
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'catalog.context_processors.muelte',
],
},
},
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
WSGI_APPLICATION = 'tests.wsgi.application'
# 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
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/
'<<strong>我尝试/strong>
import urllib.parse, urllib.request
base = 'http://localhost:8000/'
login_path = 'accounts/login/'
blurl = urllib.parse.urljoin(base, login_path)
headers = {
'username': 'l0new0lf',
'password': 'ColdSOul',
}
rq = urllib.request.Request(blurl, method='post', headers=headers)
print(urllib.request.urlopen(rq))
回溯:
Traceback (most recent call last):
File "/home/l0new0lf/Desktop/algo.py", line 11, in <module>
print(urllib.request.urlopen(rq))
File "/usr/lib/python3.8/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.8/urllib/request.py", line 531, in open
response = meth(req, response)
File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response
response = self.parent.error(
File "/usr/lib/python3.8/urllib/request.py", line 569, in error
return self._call_chain(*args)
File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/usr/lib/python3.8/urllib/request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
# # # #编辑1# # # #
我注意到我缺少csrf令牌,将其添加到POST头,但仍然是相同的错误。虽然这种方法不起作用,因为AFAIK每个csrf令牌都是为每个请求独立生成的。
import urllib.parse, urllib.request
from bs4 import BeautifulSoup
base = 'http://localhost:8000/'
login_path = 'accounts/login/'
blurl = urllib.parse.urljoin(base, login_path)
headers = {
'username': 'l0new0lf',
'password': 'ColdSOul',
}
get_rq = urllib.request.urlopen(blurl)
soup = BeautifulSoup(get_rq.read(), features='lxml')
form = soup.select_one('form')
csrf = form.select_one('form input[name^="csrf"]')
headers.update(((csrf['name'], csrf['value']),))
rq = urllib.request.Request(blurl, method='post', headers=headers)
print(urllib.request.urlopen(rq))
PD:我没有遇到这个问题,只有当身份验证,但也张贴任何数据到任何视图。另外,我确实接受基于请求模块的答案如果更方便的话。
提前感谢。
默认情况下Django视图有CSRF令牌检查
1。检查这里的答案,使您的api测试代码工作
2。如果要删除此特性,请使用函数csrf_exempt
urlpatterns = [
path('accounts/login/', csrf_exempt(views.LoginView.as_view(template_name='accounts/login.html'), name='login')), ]
3。尝试在您的登录页面表单中测试相同的
如果您仍然面临403问题,请再次检查您的登录凭据
我询问了一些关于什么是csrf,以及如何与使用这种安全措施的web服务器通信(现在有什么体面的web服务器没有这个?),并感谢@Renjith Thankachan的回答,它给了我光明,AFAIK只有两种方法。
常规和第一种方式:
我意识到需要添加">csrfmiddlewaretoken";和相应的值,格式为key=value到POST body,也是作为头,只不过这次它的类型只是">csrftoken,,否则将无法工作.
Through Headers and second Way:这是在你选择执行xmlhttprequest的情况下,Django在文档中声明,你可以用"X-CSRFToken"指定一个头。作为其名称,因此您可以避免用csrf令牌填充POST主体的麻烦。如下所示。
AJAX虽然上面的方法可以用于AJAX POST请求,但它有一些缺点不便之处:您必须记住将CSRF令牌作为POST传入数据与每个POST请求。出于这个原因,还有另一种选择方法:在每个XMLHttpRequest上,设置一个自定义的X-CSRFToken头(as)由CSRF_HEADER_NAME设置指定)到CSRF的值令牌。这通常更容易,因为许多JavaScript框架提供允许在每个请求中设置报头的钩子。
CODE:
import urllib.parse, urllib.request
from bs4 import BeautifulSoup
import requests
base = 'http://localhost:8000/'
login_path = 'accounts/login/'
blurl = urllib.parse.urljoin(base, login_path)
get = urllib.request.urlopen(blurl)
form = {
'username': 'l0new0lf',
'password': 'DonTMind',
#PASS CSRF TOKEN THROUGH POST BODY, THIS IS THE USUAL APPROACH
'csrfmiddlewaretoken' : get.headers['set-cookie'].split('=', maxsplit=1)[1].split(';', maxsplit=1)[0],
}
csrfcookie = get.headers['set-cookie']
data = bytearray()
first = True
for item in reversed(form.items()):
if not first:
data += b'&'
else:
first = False
data += item[0].encode('ascii') + b'=' + item[1].encode('ascii')
data = bytes(data)
rq = urllib.request.Request(blurl, data=data, method='post')
rq.add_header('Cookie' , csrfcookie)
rq.add_header('Content-Type', 'application/x-www-form-urlencoded')
rq.add_header('Content-Length', str(len(data)))
#PASS CSRF TOKEN THROGH AN HTTP HEADER, this is better since we don't need to be careful about passing it in to the body each time we make a post request.
#rq.add_header('X-CSRFToken', csrfcookie)
try:
urllib.request.urlopen(rq)
except Exception as e:
print(e.status != 403)
根据需要取消注释和注释,以测试第二个解决方案。