我接到了添加HTTP认证的任务(BasicAuthAuthenticationPolicy)的金字塔应用程序,并将其添加到已经有一个 AuthTktAuthenticationPolicy 实现...
基本上,我需要创建一个RESTful API来验证用户身份(我可以使用 BasicAuthAuthenticationPolicy 来进行验证?)
有什么方法可以检查用户是在使用Web界面,还是在使用api--来检查使用哪种认证策略?
我还没有遇到过在一个金字塔应用程序中涵盖两个不同的认证策略的文档(如果可能的话)。
PS:我看到一个博客系列,开始展示如何使用金字塔框架创建一个RESTful API......。据Blogger报道,这个系列将有6篇文章,但我只找到了其中的两篇。用金字塔构建一个RESTful API -- 设置 和 用Pyramid构建RESTful API--资源与遍历. 我很期待他的最后一篇文章,用Pyramid构建一个RESTful API--身份验证和ACL,但他似乎不打算完成这个系列。"用Pyramid构建一个RESTful API -- 身份验证和ACL",但他似乎并不打算完成这个系列。
总结一下我的问题。
任何帮助都将是感激的。
Pyramid并不能很容易地对应用程序的不同部分使用不同的策略(也许可以通过自定义装饰器来解决),但对于多个策略,请查看以下内容 pyramid_authstack. 我正在使用Session和BasicAuth策略,目的和你一样。
如果一个金字塔应用有两个认证策略并不直接,你可以有两个独立的金字塔应用,每个应用都有不同的策略,并组装成一个WSGI堆栈。每个应用都可以导入相同的Python代码,所以,本质上,它将是两个使用相同视图和一切的启动文件。
如果你的应用有不同的URL,你可以使用 粘贴.urlmap 如果你的要求比较复杂,你甚至可以写自己的路由器(比如说,带有某个HTTP头的请求会被路由到一个应用程序,而没有HTTP头的请求会被路由到另一个应用程序)。
所以我做的是我合并了金字塔。BasicAuthAuthenticationPolicy
和 CallbackAuthenticationPolicy
而我的结局是 这个.
我已经修改了 callback
的方法来使用 redis
会议
要使用这个类(HTTPAthentication),你可以做一些类似的事情(这是我在我的案例中实现的一个例子)。
def _get_userid(details, request):
userre = re.compile("""^([a-zA-Z1-9\.]+):([a-zA-Z1-9\.:-]+)$""", re.I)
userpass = base64.b64decode(details[1])
res = userre.search(userpass)
if res:
return res.group()[0]
def authcheck(username, password, request):
user = Users.by_username(username, enabled=True)
host = request.registry.settings.get("authentication.host", "127.0.0.1")
maxattempts = request.registry.settings.get("authentication.maxattempts",5)
base = _get_userid(request.authorization, request)
if request.redis.exists("pimssess:%s" % base64.b64encode(request.remote_addr+":"+base)):
store = pickle.loads(request.redis.get("pimssess:%s" % base64.b64encode(request.remote_addr+":"+base)))
if store.get("auth.attempts").get(request.remote_addr):
if store["auth.attempts"][request.remote_addr] >= maxattempts:
raise HTTPMethodNotAllowed(body="You have been locked out for 5 minutes")
if user and user.agent and not user.is_http_auth:
raise HTTPMethodNotAllowed(body="You are not permitted http access")
if user and user.agent and user.host != host:
raise HTTPMethodNotAllowed(body="Your host is not permitted http access")
if user and user.agent and not user.validate_password(password):
time.sleep(1.5)
raise HTTPForbidden(body="Failed login, Incorrect password")
return getGroups(username)
getGroups函数重试一个列表,其中包括 groups
隶属于用户的,即 ['admin', 'reporting']
我按照这个例子。BasicAuthAuthenticationPolicy(滚到底部)
而对于web界面的登录(CallbackAuthentication),你要创建一个登录界面,并创建视图来适应模板(检查密码和用户名是否匹配等)
哦,我差点忘了... 在你的项目中 __init__.py
,当你调用 AuthPolicy
,在 def main(...)
. 我做了。
authentication = AuthPolicy(secret='@#^&*$!DSYUIDSA8321789DS',
hashalg='sha512', check=authcheck, debug=True)
authorization = ACLAuthorizationPolicy()
config = Configurator(settings=settings, root_factory=RootFactory,
authentication_policy=authentication,
authorization_policy=authorization)
我希望这能帮助别人