我的网站使用Django的默认认证模块进行用户认证。通常,用户只需要在登录页面上填写用户名和密码并点击提交按钮,然后经过CSRF保护的数据将被发布到Django认证终端/auth/login/
。
但出于某种原因,我现在还需要在我的服务器上进行此操作。这与后端身份验证服务器相同。经过研究和试错,我最终得到了:
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
import requests
class fb_login(View):
"login view for Facebook OAuth"
@method_decorator(csrf_protect)
def get(self, request):
''' code that gets username and password info. from user's FB profile
is not shown here '''
# login code
url = 'http://localhost:8000/auth/login/'
client = requests.session()
# Retrieve the CSRF token first
client.get(url) # sets cookie
csrftoken = client.cookies['csrftoken']
form = {'username': uname, 'password': pw}
header = {'X-CSRFToken': csrftoken}
resp = requests.post(url, data=form, headers=header)
我也尝试将csrf令牌添加为表单字段的一部分:
form = {'username': uname, 'password': pw , 'csrfmiddlewaretoken': csrftoken}
resp = requests.post(url, data=form)
我基本上只是按照Django文档操作。但我仍然遇到了403错误,提示CSRF verification failed, CSRF cookie not set
。我想知道我是否漏掉了什么步骤?我已经仔细检查了Django文档中的过程,但我找不到任何可能出错或遗漏的地方。
{% csrf_token %}
? - John Gordoncsrfmiddlewaretoken=xxx
和 cookiecsrftoken=xxx
。也许你需要设置 cookie 而不是/以及表单字段。 - rodrigorender()
函数,并且它会自动处理。请参阅文档以了解其他选择。 - rodrigo