我使用python模块将我的凭据发布到一个用于登录的通用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/‘我的尝试’
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: --我不仅在身份验证时遇到这个问题,而且在POSTing中任何数据到任何视图时都会遇到这个问题。此外,如果更方便的话,我也接受基于请求模块的答案。
在此之前,非常感谢您。
发布于 2021-03-12 05:48:10
发布于 2021-03-13 21:51:37
我询问了一下csrf是什么,以及如何与使用这种安全措施的ways服务器进行通信(现在有什么像样的ways服务器没有这种功能?),感谢@Renjith Thankachan的回答给我带来了光明,AFAIK只有两种方式。
传统和第一条路:
我意识到,需要将"csrfmiddlewaretoken“及其各自的值(格式为key=value )添加到POST body中,也将其作为一个标头,但这一次只键入为"csrftoken",否则将无法工作。
通过头和第二种方式:-这是在您选择执行XMLHtppRequest的情况下,Django在文档中声明,您可以指定一个以“X”作为其名称的标头,这样您就可以消除用csrf令牌填充POST正文的麻烦。正如下面所述。
阿贾克斯 虽然上面的方法可以用于AJAX POST请求,但它有一些不便之处:您必须记住将CSRF令牌作为POST数据与每个POST请求一起传递。因此,有另一种方法:在每个XMLHttpRequest上,将自定义的alternative标头(由CSRF_HEADER_NAME设置指定)设置为CSRF令牌的值。这通常更容易,因为许多JavaScript框架提供了允许在每个请求上设置头的挂钩。
用代码表示的:
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)根据需要取消注释和注释,以测试第二个解决方案。
https://stackoverflow.com/questions/66594493
复制相似问题