【问题标题】:Token-based Authentication with Cornice for Pyramid用于 Pyramid 的 Cornice 基于令牌的身份验证
【发布时间】:2017-07-06 17:12:57
【问题描述】:

我正在使用在 Pyramid 应用程序中开发 RESTful API 的资源策略。 http://cornice.readthedocs.io/en/latest/resources.html。但是我找不到为 API 添加身份验证的示例。非常感谢任何指导。

【问题讨论】:

标签: rest pyramid cornice


【解决方案1】:

正如 Antoine Leclair 所指出的,Cornice 依赖于 Pyramid。您必须在应用初始化期间启用授权和身份验证策略。例如(这里使用pyramid-jwt):

from pyramid.config import Configurator
from pyramid.authorization import ACLAuthorizationPolicy

def main():
    config = Configurator()
    # Pyramid requires an authorization policy to be active.
    config.set_authorization_policy(ACLAuthorizationPolicy())
    # Enable JWT authentication.
    config.include('pyramid_jwt')
    config.set_jwt_authentication_policy('secret')

您还可以通过从pyramid.authentication 中的内置 Pyramid 类继承来创建自己的策略:

from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy
from zope.interface import implementer

@implementer(IAuthenticationPolicy)
class MyAuthenticationPolicy(CallbackAuthenticationPolicy):
    def __init__(self, realm='Realm'):
        self.realm = realm

    def unauthenticated_userid(self, request):
        user_id = self._get_credentials(request)
        return user_id

    def forget(self, request):
        return [('WWW-Authenticate', 'MyAuth realm="%s"' % self.realm)]

    def _get_credentials(self, request):
        authorization = request.headers.get('Authorization', '')
        # your own strategy...
        # if valid: return user_id
        # else return None

查看awesome-pyramid 上的现有项目,看看您需要的东西是否已经存在...

【讨论】:

  • 我们为 Kinto 项目的 Portier、Firefox 帐户、Github 实施了一堆身份验证策略,您可能想看看它们。
猜你喜欢
  • 2016-01-23
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2012-03-19
  • 2017-07-10
  • 2020-03-03
相关资源
最近更新 更多