开发者

how to get auth_user in python web request

I'm new to python . I want to make a basic auth in a web project , is there any way get HTTP authentication variables like the '$_S开发者_高级运维ERVER['php_auth_user']' in php ? I'm using the FF's torando server.


There doesn't seem to be any particular support for Basic auth in Tornado, so you'd have to do it yourself by base64-decoding the Authorization header.

Probably something like:

import base64

class BasicAuthHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        scheme, _, token= self.request.headers.get('Authorization', '').partition(' ')
        if scheme.lower()=='basic':
            user, _, pwd= base64.decodestring(token).partition(':')
            # if pwd matches user:
                return user
        return None

    def get(self):
        if not self.get_current_user():
            self.set_status(401)
            self.set_header('WWW-Authenticate', 'basic realm="Example site"')
            # produce error/login page for user to see if they press escape to
            # cancel authorisation
            return

(not tested as I don't run Tornado.)


The tornado-http-auth module provides basic and digest authentication for Tornado. A brief usage example would be:

import tornado.ioloop
from tornado_http_auth import BasicAuthMixin
from tornado.web import RequestHandler, Application

class MainHandler(BasicAuthMixin, RequestHandler):
    def prepare(self):
        self.get_authenticated_user(realm='Protected', auth_func=credentials.get)

    def get(self):
        self.write('Hello %s' % self._current_user)

app = Application([
    (r'/', MainHandler),
])

app.listen(8080)
tornado.ioloop.IOLoop.current().start()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜