我编写了一个简单的 Python 脚本,可以登录到 Shibbolized 页面。
首先,我在 Firefox 中使用 Live HTTP Headers 来观察我所针对的特定 Shibbolized 页面的重定向。
urllib.request
然后我使用(在 Python 3.4 中,但urllib2
在 Python 2.x 中似乎具有相同的功能)编写了一个简单的脚本。我发现默认的重定向跟踪urllib.request
符合我的目的,但是我发现子类很好,urllib.request.HTTPRedirectHandler
并且在这个子类(类ShibRedirectHandler
)中为所有 http_error_302 事件添加一个处理程序。
在这个子类中,我只是打印出参数的值(用于调试目的);请注意,为了使用默认重定向跟随,您需要结束处理程序return HTTPRedirectHandler.http_error_302(self, args...)
(即调用基类 http_errror_302 处理程序。)
urllib
使用 Shibbolized Authentication最重要的组件是创建OpenerDirector
添加了 Cookie 处理的组件。OpenerDirector
您使用以下内容构建:
cookieprocessor = urllib.request.HTTPCookieProcessor()
opener = urllib.request.build_opener(ShibRedirectHandler, cookieprocessor)
response = opener.open("https://shib.page.org")
这是一个完整的脚本,可以帮助您入门(您需要更改我提供的一些模拟 URL,并输入有效的用户名和密码)。这使用 Python 3 类;为了在 Python2 中进行这项工作,请将 urllib.request 替换为 urllib2 并将 urlib.parse 替换为 urlparse:
import urllib.request
import urllib.parse
#Subclass of HTTPRedirectHandler. Does not do much, but is very
#verbose. prints out all the redirects. Compaire with what you see
#from looking at your browsers redirects (using live HTTP Headers or similar)
class ShibRedirectHandler (urllib.request.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
print (req)
print (fp.geturl())
print (code)
print (msg)
print (headers)
#without this return (passing parameters onto baseclass)
#redirect following will not happen automatically for you.
return urllib.request.HTTPRedirectHandler.http_error_302(self,
req,
fp,
code,
msg,
headers)
cookieprocessor = urllib.request.HTTPCookieProcessor()
opener = urllib.request.build_opener(ShibRedirectHandler, cookieprocessor)
#Edit: should be the URL of the site/page you want to load that is protected with Shibboleth
(opener.open("https://shibbolized.site.example").read())
#Inspect the page source of the Shibboleth login form; find the input names for the username
#and password, and edit according to the dictionary keys here to match your input names
loginData = urllib.parse.urlencode({'username':'<your-username>', 'password':'<your-password>'})
bLoginData = loginData.encode('ascii')
#By looking at the source of your Shib login form, find the URL the form action posts back to
#hard code this URL in the mock URL presented below.
#Make sure you include the URL, port number and path
response = opener.open("https://test-idp.server.example", bLoginData)
#See what you got.
print (response.read())