问题描述
重定向后,我对HTTP基本身份验证有一个快速的问题.
I have a quick question regarding HTTP Basic Authentication after a redirect.
我正尝试登录到一个网站,由于操作原因,该网站立即使用HTTP 302响应将我重定向到中央登录网站.在我的测试中,重定向后请求模块似乎没有将我的凭据发送到中央登录站点.如下面的代码片段所示,我被迫从响应对象中提取重定向URL,然后再次尝试登录.
I am trying to login to a website which, for operational reasons, immediately redirects me to a central login site using an HTTP 302 response. In my testing, it appears that the Requests module does not send my credentials to the central login site after the redirect. As seen in the code snippet below, I am forced to extract the redirect URL from the response object and attempt the login again.
我的问题很简单:
有没有一种方法可以在脱机重定向后强制请求重新发送登录凭据?
My question is simply this:
is there a way to force Requests to re-send login credentials after a redirect off-host?
出于可移植性的原因,我宁愿不使用.netrc文件.另外,该网站的提供者已将url_login设为静态,但未对url_redirect做出任何声明.
For portability reasons, I would prefer not to use a .netrc file. Also, the provider of the website has made url_login static but has made no such claim about url_redirect.
感谢您的时间!
代码片段
import requests
url_login = '<url_login>'
myauth = ('<username>', '<password')
login1 = requests.request('get', url_login, auth=myauth)
# this login fails; response object contains the login form information
url_redirect = login1.url
login2 = requests.request('get', url_redirect, auth=myauth)
# this login succeeds; response object contains a welcome message
更新
这是上面通用代码的更具体版本.
Here is a more specific version of the general code above.
- 第一个
request()
返回HTTP 200响应,并在其文本字段中包含表单信息. - 第二个
request()
返回其文本字段中带有'HTTP Basic: Access denied.'
的HTTP 401响应.
- The first
request()
returns an HTTP 200 response and has the form information in its text field. - The second
request()
returns an HTTP 401 response with'HTTP Basic: Access denied.'
in its text field.
(当然,如果提供有效的凭据,登录将成功.)
(Of course, the login succeeds when provided with valid credentials.)
再次,我想知道是否仅通过一次调用requests.request()
就能实现所需的登录.
Again, I am wondering whether I can achieve my desired login with only one call to requests.request()
.
import requests
url_login = 'http://cddis-basin.gsfc.nasa.gov/CDDIS_FileUpload/login'
myauth = ('<username>', '<password>')
with requests.session() as s:
login1 = s.request('get', url_login, auth=myauth)
url_earthdata = login1.url
login2 = s.request('get', url_earthdata, auth=myauth)
推荐答案
对此,我的解决方案是使用会话".这是实现会话的方法.
My solution to this would be use of "Session". Here is how you can implement Session.
import requests
s = requests.session()
url_login = "<loginUrl>"
payload = {
"username": "<user>",
"password": "<pass>"
}
req1 = s.post(url_login, data=payload)
# Now to make sure you do not get the "Access denied", use the same session variable for the request.
req2 = s.get(url_earthdata)
这应该可以解决您的问题.
This should solve your problem.
这篇关于Python请求-重定向后的身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!