python – 在金字塔中使用http标头进行身份验证
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 在金字塔中使用http标头进行身份验证,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5447字,纯文字阅读大概需要8分钟。
内容图文
![python – 在金字塔中使用http标头进行身份验证](/upload/InfoBanner/zyjiaocheng/763/a6ee0349d8ae4af4b387305572ac3182.jpg)
我一直在寻找一种方法来验证用户和http头传递的密码.
curl --user user1:pass1 http://localhost:6543/the_resource
我们的想法是检查传递的凭据是否允许用户查看* the_resource *,如果不返回401 – 禁止.
我发现只有身份验证策略的例子,其中必须有登录和注销视图或this basic authentication policy,我不知道如何与Pyramid的ACL绑定.
我会感激任何帮助,如何开始.
还有一件事在我脑海里浮现.如何强制这个pup-up登录窗口进行基本身份验证?
解决方法:
最后,很明显如何使用身份验证和授权.一切都是实际写的我只是没有立即抓住这个概念.我会试着写下我是如何以一种无声的方式解释它,我必须自己解释一下.我希望它对某人有用.最后的来源可能有助于理解我的写作;)欢迎所有评论.如果我出错了,请纠正我.
认证
最重要的是basic authentication,其中BasicAuthenticationPolicy必须具有以后可以在金字塔应用程序中使用的方法 – 例如authenticated_userid(request).这些方法使用_get_basicauth_credentials()来提取在http标头中传递的登录名和密码.在mycheck()中实际检查登录名和密码是否正确.
现在在__init__.py中我们必须使用方法mycheck作为参数添加BasicAuthenticationPolicy作为我们的应用程序配置器的参数,因此金字塔可以使用它.
在认证问题上都是如此.现在,您应该能够使用authenticated_userid(request)进行身份验证以及身份验证(请参阅views.py)
授权
要对资源使用金字塔授权,我们需要在__init__.py中将ACLAuthorizationPolicy添加到我们的配置器中,并将__acl__添加到资源中.在大多数简单的情况下,root_factory(参见this和this)ACL定义哪个组具有哪些权限.如果我没有弄错(允许,’组:观众’,’视图’)’组:观众’必须是什么认证方法 – mycheck() – 返回.
授权的最后一步是使用装饰器(或在add_route中)为某些视图添加权限.如果我们将ACL权限 – 视图 – 添加到view_page,则组:允许查看者查看该页面(调用view_page).
basic_authentication.py
import binascii
from zope.interface import implements
from paste.httpheaders import AUTHORIZATION
from paste.httpheaders import WWW_AUTHENTICATE
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import Everyone
from pyramid.security import Authenticated
import yaml
def mycheck(credentials, request):
login = credentials['login']
password = credentials['password']
USERS = {'user1':'pass1',
'user2':'pass2'}
GROUPS = {'user1':['group:viewers'],
'user2':['group:editors']}
if login in USERS and USERS[login] == password:
return GROUPS.get(login, [])
else:
return None
def _get_basicauth_credentials(request):
authorization = AUTHORIZATION(request.environ)
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enough values to unpack
return None
if authmeth.lower() == 'basic':
try:
auth = auth.strip().decode('base64')
except binascii.Error: # can't decode
return None
try:
login, password = auth.split(':', 1)
except ValueError: # not enough values to unpack
return None
return {'login':login, 'password':password}
return None
class BasicAuthenticationPolicy(object):
""" A :app:`Pyramid` :term:`authentication policy` which
obtains data from basic authentication headers.
Constructor Arguments
``check``
A callback passed the credentials and the request,
expected to return None if the userid doesn't exist or a sequence
of group identifiers (possibly empty) if the user does exist.
Required.
``realm``
Default: ``Realm``. The Basic Auth realm string.
"""
implements(IAuthenticationPolicy)
def __init__(self, check, realm='Realm'):
self.check = check
self.realm = realm
def authenticated_userid(self, request):
credentials = _get_basicauth_credentials(request)
if credentials is None:
return None
userid = credentials['login']
if self.check(credentials, request) is not None: # is not None!
return userid
def effective_principals(self, request):
effective_principals = [Everyone]
credentials = _get_basicauth_credentials(request)
if credentials is None:
return effective_principals
userid = credentials['login']
groups = self.check(credentials, request)
if groups is None: # is None!
return effective_principals
effective_principals.append(Authenticated)
effective_principals.append(userid)
effective_principals.extend(groups)
return effective_principals
def unauthenticated_userid(self, request):
creds = self._get_credentials(request)
if creds is not None:
return creds['login']
return None
def remember(self, request, principal, **kw):
return []
def forget(self, request):
head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
return head
myproject.__init__.py
from pyramid.config import Configurator
from myproject.resources import Root
from myproject.basic_authentication import BasicAuthenticationPolicy, mycheck
from pyramid.authorization import ACLAuthorizationPolicy
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(root_factory='myproject.models.RootFactory',
settings=settings,
authentication_policy=BasicAuthenticationPolicy(mycheck),
authorization_policy=ACLAuthorizationPolicy(),
)
config.add_static_view('static', 'myproject:static', cache_max_age=3600)
config.add_route('view_page', '/view')
config.add_route('edit_page', '/edit')
config.scan()
app = config.make_wsgi_app()
return app
models.py
from pyramid.security import Allow
class RootFactory(object):
__acl__ = [ (Allow, 'group:viewers', 'view'),
(Allow, 'group:editors', 'edit') ]
def __init__(self, request):
pass
views.py
from pyramid.security import authenticated_userid
from pyramid.view import view_config
#def my_view(request):
# return render_to_response('templates/simple.pt', {})
@view_config(route_name='view_page', renderer='templates/view.pt', permission='view')
def view_page(request):
return {}
@view_config(route_name='edit_page', renderer='templates/edit.pt', permission='edit')
def edit_page(request):
return {}
内容总结
以上是互联网集市为您收集整理的python – 在金字塔中使用http标头进行身份验证全部内容,希望文章能够帮你解决python – 在金字塔中使用http标头进行身份验证所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。