URL中的HTTP身份验证,用户名中带有反斜杠 [英] HTTP Authentication in URL with backslash in username

查看:622
本文介绍了URL中的HTTP身份验证,用户名中带有反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要HTTP基本身份验证才能进行REST调用。在用户名中,我必须提供一个域(带有连字符),然后提供一个反斜杠以将其与用户名分开,例如: DOM-AIN\user_name 。这样密码就很不错了。

I need to HTTP Basic Auth for a REST call. In the username I have to provide a domain (which has a hyphen) and then a backslash to separate it from the username, like this: DOM-AIN\user_name. Then the password is pretty benign.

这在curl上很好用:

This works fine with curl:

curl 'https://DOM-AIN\user_name:password@myurl.com'

我现在需要将其放入Python,但是我尝试使用请求和urllib / 2/3 ...它们不喜欢 \ @ 。即使我将URL编码为%40等,它们也会被解释为实际的,并且urllib认为我正在尝试定义端口,但会出现错误:无效的套接字,我想,我忘记了。

I need to put this into Python now, but I've tried with requests and urllib/2/3...they don't like the \ : or the @. Even when I URL encode to %40, etc., those get interpreted as an actual : and urllib thinks I'm trying to define a port and I get an error: Invalid socket, I think, I forgot.

所以我尝试使用urllib3在标头中传递用户名和密码,但是我收到了未经授权的访问错误,我怀疑这是因为我需要以某种方式对用户名进行编码在标题中输入反斜杠(%5C),但这似乎也不起作用。

So I tried passing the username and password in the header using urllib3, but I get an unauthorized access error and I suspect it's because I need to somehow encode the username in the header to account for the backslash (%5C), but that doesn't seem to be working either.

以下是一些无效的代码:

Here is some code that doesn't work:

# Attempt 1
http = urllib3.PoolManager()
url1 = https://ws.....
headers = urllib3.util.make_headers(basic_auth='DOM-AIN\user_name:password')
r1 = http.request('GET', url1, headers=headers)
response = r1.data

# Attempt 2
passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
passwordManager.add_password(None, url, 'DOM-AIN\user_name, password)
authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
opener = urllib2.build_opener(authenticationHandler)
data = opener.open(url1)

还有其他请求的尝试,但我已经没有了。如果有用的话,我会得到这些错误,但是如果已经有已知的事情我做错了,那将会很好...

There were some other attempts with request, but I don't have those anymore. I can get the errors of these if it would be useful, but if there is already a known thing I'm doing wrong that would be great...

推荐答案

反斜线应在Python字符串文字中转义:

Backslash should be escaped in Python string literals:

username = 'DOM-AIN\\user_name' # OR
username = r'DOM-AIN\user_name' # raw-string literal

示例:

import urllib2, base64

request = urllib2.Request('https://example.com')
credentials = base64.b64encode(username + b':' + password)
request.add_header('Authorization', b'Basic ' + credentials)
response = urllib2.urlopen(request) 

注意:与 HTTPBasicAuthHandler 代码;它总是发送凭据而不用等待 WWW-Authenticate 标头的 401 响应。

Note: unlike HTTPBasicAuthHandler code; it always sends the credentials without waiting for 401 response with WWW-Authenticate header.

这篇关于URL中的HTTP身份验证,用户名中带有反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆