当休息。谁身份验证失败?

2024-05-16 00:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个^{} plugin,希望从repoze.who身份验证中间件返回JSON,并且仍然控制HTTP状态代码。如何做到这一点?你知道吗


Tags: 中间件代码身份验证jsonhttp状态pluginrepoze
1条回答
网友
1楼 · 发布于 2024-05-16 00:20:24

实现这一点的一种方法是实现^{} Challenger接口。下面的解决方案利用了^{}中的WebOb异常可以用作WSGI应用程序这一事实。下面的示例显示了如何在假设的Facebook插件中使用它,其中2.x API允许用户而不是授予对其电子邮件的访问权限,这可能是成功注册/身份验证所必需的:

import json
from webob.acceptparse import MIMEAccept
from webob.exc import HTTPUnauthorized, HTTPBadRequest


FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED = 'repoze.who.facebook_connect.not_granted'


class ExampleJSONChallengerPlugin(object):
    json_content_type = 'application/json'
    mime_candidates = ['text/html',
                       'application/xhtml+xml',
                       json_content_type,
                       'application/xml',
                       'text/xml']

    def is_json_request_env(self, environ):
        """Checks whether the current request is a json request as deemed by
        TurboGears (i.e. response_type is already set) or if the http
        accept header favours 'application/json' over html.
        """
        if environ['PATH_INFO'].endswith('.json'):
            return True

        if 'HTTP_ACCEPT' not in environ:
            return False

        # Try to mimic what Decoration.lookup_template_engine() does.
        return MIMEAccept(environ['HTTP_ACCEPT']) \
            .best_match(self.mime_candidates) is self.json_content_type

    def challenge(self, environ, status, app_headers, forget_headers):
        if FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED in environ:
            response = HTTPBadRequest(detail={
                'not_granted': 
                environ.pop(FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED),
            })
        elif status.startswith('401 '):
            response = HTTPUnauthorized()
        else:
            response = None

        if response is not None and self.is_json_request_env(environ):
            response.body = json.dumps({
                'code': response.code,
                'status': response.title,
                'explanation': response.explanation,
                'detail': response.detail,
            })
            response.content_type = self.json_content_type

        return response

这里的一个中心点是response,一个webob.exc.WSGIHTTPException的子类的实例,被用作WSGI应用程序,但是如果responsebody属性被设置,那么它就不是自动生成的,这是我们用来显式地将响应的主体设置为字典的JSON格式的字符串表示的事实。如果在处理对以“.json”结尾的URL或Accept头包含application/json的请求期间调用上述质询程序,则响应的主体可能呈现如下形式:

{
    "status": "Bad Request",
    "explanation": "The server could not comply with the request since it is either malformed or otherwise incorrect.",
    "code": 400, 
    "detail": {"not_granted": ["email"]}
}

如果不是,则正文将呈现为HTML:

<html>
 <head>
  <title>400 Bad Request</title>
 </head>
 <body>
  <h1>400 Bad Request</h1>
  The server could not comply with the request since it is either 
  malformed or otherwise incorrect.<br /><br />
{'not_granted': [u'email']}


 </body>
</html>

相关问题 更多 >