python – 在金字塔中使用http标头进行身份验证

我一直在寻找一种方法来验证用户和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(参见thisthis)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标头进行身份验证 - 代码日志