首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Cornice for Pyramid进行基于令牌的身份验证

使用Cornice for Pyramid进行基于令牌的身份验证
EN

Stack Overflow用户
提问于 2017-07-03 12:08:04
回答 1查看 978关注 0票数 4

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

EN

回答 1

Stack Overflow用户

发布于 2017-07-06 17:12:57

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

代码语言:javascript
复制
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中的内置金字塔类来创建自己的策略

代码语言:javascript
复制
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上的现有项目,看看您需要的内容是否已经存在……

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44877666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档