使用python登录asp.net web应用程序

使用python登录asp.net web应用程序,python,asp.net,authentication,python-requests,Python,Asp.net,Authentication,Python Requests,我试图用python登录到一个web应用程序,但每次尝试都以500个错误结束,html正文显示错误:[HttpAntiforyException]。我试着应用其他问题的一些解决方案,但没有任何帮助。所以现在,我被第一个请求吸引住了,这个响应给了我500 import requests from bs4 import BeautifulSoup url = "http://localhost:52053/Account/Login" username = "test@test.sk" use

我试图用python登录到一个web应用程序,但每次尝试都以500个错误结束,html正文显示错误:[HttpAntiforyException]。我试着应用其他问题的一些解决方案,但没有任何帮助。所以现在,我被第一个请求吸引住了,这个响应给了我500

import requests
from bs4 import BeautifulSoup 

url = "http://localhost:52053/Account/Login"

username = "test@test.sk"
user_password = "pass"

session = requests.Session()
response = session.get(url)
soup = BeautifulSoup(response.content, features="html.parser")
#print(soup)
states = ["__RequestVerificationToken", "Email", "RememberMe"]
login_data = {"username": username, "password": user_password, "Login": "submit"}
headers = {"Host": "localhost:52053",
           "Content-Type": "application/x-www-form-urlencoded",
           "Connection": "close",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0)",
           "Cookie": str(session.cookies.get_dict())}

for state in states:  # search for existing aspnet states and get its values
    result = soup.find('input', {'name': state})
    if not (result is None):  # when existent (some may not be needed!)
        if state == "Email":
            login_data.update({state: login_data["username"]})
        else:
            login_data.update({state: result['value']})


post_request = session.post(url, headers=headers, data=login_data)
成功的登录尝试如下所示

POST /Account/Login HTTP/1.1
Host: localhost:52053
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: sk,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 193
Origin: http://localhost:52053
Connection: close
Referer: http://localhost:52053/Account/Login
Cookie: __RequestVerificationToken=j9yFGpTFSlH5_aQt0k-Gvz10I16TVXbDk31NKPm1HkcWsksUfKXkjL567yFplCS_VovTR7lVuEgNjwgp-EO3RjNj4gQOvNUXnPkjymZx_jA1
Upgrade-Insecure-Requests: 1

__RequestVerificationToken=LjHuOdKSCr1A7KRDNie4GUnCZ3qRwUCdHyLlPYT40DsEB-GNUvEKxe5nvZWf5gZ4ZflwI43xGWPyYu8GI15wroEg9WRRVtSzZ9-KY9Mu_JA1&Email=test%40test.sk&Password=pass&RememberMe=false
回应如下:

HTTP/1.1 302 Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: /
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
Set-Cookie: .AspNet.ExternalCookie=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
Set-Cookie: .AspNet.ApplicationCookie=KCLm03FHj8v_6rIpTzBTm7EzEtzpKmIz1Z9_z29wycUSqUVyKbGEmptXUwG41MqNOMR7Vbeq2u576ijazupNLffLP-Ua0n60aLmnVSDsLsdTqYT7jjqyGPw1Ppp8AnIDs3sdefmksazX2UvKTxzxRBufFCoxtCJx51mWtBv7v0JzUeC1hnfu1AIJ7GH_8T59KD3iv0hRSHDqlWHlkWzyN1Xt0m5ixC14e4eC2YxEm3_acy96atB2Jv5u0HREPzssLmywuzj6sLa9cHCllTG2gMVWvHA3IDhCWu7Ojf8BO02Eml3pPM5QTJ-sq540fcj9QyELayUOwBZWffSgsJeq8mlt3FupQcJ-JTJxDzAsDc4Cmk-BcvYSfpAJq4SdR-Y4mTN_6vu-wwAOLZPSgh-5K7guWmZ3VfRitZHXd_rvTEmMiVrgHFTEQAkUYu4zTSupxRplTtKb1VSDs0Nc1uEos2z0_aw-nBbRBrTPpvmqGok
验证流继续执行此请求。我还没有发送这个请求(我把它放在这里只是为了更好的想象):

下一个回答大概是200-你在

所以我的问题是第一个请求的响应失败了。有人能看到一些错误,还是我忘了什么

第一次请求调用的响应失败:

HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUENBZG1pbmlzdHJhdG9yXERlc2t0b3BccGVuIHRlc3RpbmdcU2VjdXJpdHlXb3Jrc2hvcC1EVldBLW1hc3RlclxkdndhLXRyYWluaW5nXGR2d2EtdHJhaW5pbmdcQWNjb3VudFxMb2dpbg==?=
如果我尝试删除请求头和登录数据,结果是:

打印(post_请求.请求.标题)

打印(登录数据)


我只是找到了解决办法

请求可以自己处理所有的报头(由于某种原因,我的报头会导致错误),它将我的请求重定向到200响应,所以我没有立即看到,它实际上正在工作并捕获302响应

我通过印刷发现:

print(post_request.history)
这给了我

现在,当我知道有一个重定向时,我只需要
allow_redirects=False
就可以捕获我的set cookie头了

完整代码,witch收到的预期响应为:

import requests
from bs4 import BeautifulSoup

url = "http://localhost:52053/Account/Login"
username = "test@test.sk"
user_password = "pass"

session = requests.Session()
response = session.get(url)
soup = BeautifulSoup(response.content, features="html.parser")
#print(soup)
states = ["__RequestVerificationToken", "Email", "RememberMe"]
login_data = {"username": username, "password": user_password, "Login": "submit"}

for state in states:  # search for existing aspnet states and get its values
    result = soup.find('input', {'name': state})
    if not (result is None):  # when existent (some may not be needed!)
        if state == "Email":
            login_data.update({state: login_data["username"]})
        else:
            login_data.update({state: result['value']})


post_request = session.post(url,  data=login_data, allow_redirects=False)

print(login_data)

#the code below is testing, if the HttpAntiForgeryException is in code

if "HttpAntiForgeryException" not in post_request.text:
    print(post_request.headers)
else:
    print("antiforgery")

问题可能是您没有在body或cookie中传递
\uu RequestVerificationToken
,或者它们不匹配。我理解这一点__RequestVerificationToken应该在那里(至少,当我打印标题时,它在那里)。我只是在想,他们是否有不匹配的地方,或者请求的构建很糟糕,但我无法理解。
{'username': 'test@test.sk', 'password': 'pass', 'Login': 'submit', '__RequestVerificationToken': '14OuwaRqldlGKi93C91zf6QD_ouOorHBDe63s4KgfP3gbt85V0QMy2X5OMwWAo1TUrD8zJ-zoZbXLPpgDI_wrxVZv3ceYNos_e5_elFhVt01', 'Email': 'test@test.sk', 'RememberMe': 'true', 'Password': 'pass'}
print(post_request.history)
import requests
from bs4 import BeautifulSoup

url = "http://localhost:52053/Account/Login"
username = "test@test.sk"
user_password = "pass"

session = requests.Session()
response = session.get(url)
soup = BeautifulSoup(response.content, features="html.parser")
#print(soup)
states = ["__RequestVerificationToken", "Email", "RememberMe"]
login_data = {"username": username, "password": user_password, "Login": "submit"}

for state in states:  # search for existing aspnet states and get its values
    result = soup.find('input', {'name': state})
    if not (result is None):  # when existent (some may not be needed!)
        if state == "Email":
            login_data.update({state: login_data["username"]})
        else:
            login_data.update({state: result['value']})


post_request = session.post(url,  data=login_data, allow_redirects=False)

print(login_data)

#the code below is testing, if the HttpAntiForgeryException is in code

if "HttpAntiForgeryException" not in post_request.text:
    print(post_request.headers)
else:
    print("antiforgery")