我收到了将 HTTP 身份验证(BasicAuthAuthenticationPolicy)添加到已经实现了 AuthTktAuthenticationPolicy 的 Pyramid 应用程序的任务...
基本上我需要创建一个 RESTful API 来验证用户(我可以为此使用 BasicAuthAuthenticationPolicy 吗?)。
有没有办法检查用户是使用网络界面还是使用 api - 以检查要使用的身份验证策略?
我还没有遇到过在单个 Pyramid 应用程序中涵盖两种不同身份验证策略的文档(如果可能的话)。
附言:
我遇到了一个开始展示如何使用 Pyramid 框架创建 RESTful API 的博客系列......博客报告说系列中将有 6 篇文章,但我只找到了其中两篇文章:Building a RESTful API with Pyramid - Setup和 Building a RESTful API with Pyramid - Resource and Traversal 。我很期待他的最后一篇文章:使用 Pyramid 构建 RESTful API - 身份验证和 ACL,但他似乎不会完成这个系列。
回顾一下我的问题:
- 我可以使用 BasicAuthAuthenticationPolicy 构建 RESTful API 来验证用户身份吗?
- 有没有办法检查用户是在使用网络界面,还是在使用 API - 以检查要使用的身份验证策略?
我们将不胜感激。
最佳答案
所以我所做的是合并 Pyramids BasicAuthAuthenticationPolicy
和 CallbackAuthenticationPolicy
,最后得到 this .
我修改了 callback
方法以使用 redis
session
要使用此类 (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),您创建一个登录界面,并创建 View 以适应模板(检查密码和用户名匹配等)
哦,我差点忘了...在你的项目 __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)
我确实希望这可以帮助某人。
关于python - Pyramid 中的多重身份验证策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28740736/