Home > Article > Backend Development > How to implement user identity authentication under Tornado in Python
There is a current_user attribute in Tornado's RequestHandler class that is used to save the user name of the current request. The default value of RequestHandler.get_current_user is None. This attribute can be read at any time in processing functions such as get() and post() to obtain the current user name. RequestHandler.current_user is a read-only property, so if you want to set the property value, you need to overload the RequestHandler.get_current_user() function to set the property value.
Example: Use the RequestHandler.current_user attribute and the RequestHandler.get_current_user() method to implement user identity control.
Code:
import tornado.web import tornado.ioloop import uuid #UUID 生成库 dict_sessions={} #保存所有登录的Session class BaseHandler(tornado.web.RequestHandler): #公共基类 #写入current_user的函数 def get_current_user(self): session_id=self.get_secure_cookie("session_id") return dict_sessions.get(session_id) class MainHandler(BaseHandler): @tornado.web.authenticated #需要身份认证才能访问的处理器 def get(self): name=tornado.escape.xhtml_escape(self.current_user) self.write("Hello,"+name) class LoginHandler(BaseHandler): def get(self): #登陆页面 self.write('<html><>body' '<form action="/login" method="post">' 'Name:<input type="text" name="name">' '<input type="submit" value="Sign in">' '</form></body></html>') def post(self): #验证是否运行登陆 if len(self.get_argument("name"))<3: self.redirect("/login") session_id=str(uuid.uuid1()) dict_sessions[session_id]=self.get_argument("name") self.set_secure_cookie("session_id",session_id) self.redirect("/") setting={ "cookie_secret":"SECRET_DONT_LEAK", #Cookie加密秘钥 "login_url":"/login" #定义登陆页面 } application=tornado.web.Application([ (r"/",MainHandler), #URL映射定义 (r"/login",LoginHandler) ],**setting) def main(): application.listen(8888) tornado.ioloop.IOLoop.current().start() #挂起监听 if __name__ == '__main__': main()
This example demonstrates a complete identity authentication programming framework. The overall idea is as follows:
Use the global dictionary dict_sessions to save logged in User information, for simplicity, this example only saves the key-value pair of [Reply ID: Username].
Define the public base class BaseHandler, which inherits from tornado.web.RequestHandler and is used to define the public properties and behaviors of all processors on this website. Overload its get_current_user() function, which is automatically called by Tornado when accessing the RequestHandler.current_user property. This function first uses get_secure_cookie() to obtain the session ID of this visit, and then uses the ID to obtain the user name from dict_sessions and returns it.
The MainHandler class is a handler instance that requires users to be authenticated before accessing. The processing function get() in this processor uses the decorator tornado.web.authenticated. Before execution, the processing function with this decorator determines the user's authentication status based on whether current_user has been assigned a value. If it has been assigned, it can Do the normal logic, otherwise automatically redirect to the website's login page.
The LoginHandler class is a login page processor, its get() function is used to render the login page, and the post() function is used to verify whether the user is allowed to log in.
In the initialization function of tornado.web.Application, the login page address of the website is given through the login_url parameter. This address is used by the tornado.web.authenticated decorator to redirect to a URL when it is discovered that the user has not been authenticated.
Note: All page handlers that join identity authentication need to inherit from the BaseHandler class instead of directly inheriting the original tornado.web.RequestHandler class.
Commercial identity authentication needs to improve more content, such as adding password verification mechanisms, managing login timeouts, and saving user information to the database.
The above is the detailed content of How to implement user identity authentication under Tornado in Python. For more information, please follow other related articles on the PHP Chinese website!