【Tornado】API接口使用Basic Auth認證

1、拿到認證請求

2、解碼

3、與數據庫中的用戶進行比對 

4、如果請求沒有攜帶basic auth信息,瀏覽器彈框輸入

5、basic信息錯誤,還是繼續彈框輸入

class BasicAuthHandler(tornado.web.RequestHandler):

    def initialize(self, db):
        self.db = db

    def create_auth_header(self):
        self.set_status(401)
        self.set_header('WWW-Authenticate', 'Basic realm=Restricted')
        self._transforms = []
        self.finish()

    def get(self):
        db = self.db
        cursor = db.cursor(pymysql.cursors.DictCursor)
        # Authorization: Basic base64("user:passwd")
        auth_header = self.request.headers.get('Authorization', None)
        if auth_header is not None:
            # Basic Zm9vOmJhcg==
            auth_mode, auth_base64 = auth_header.split(' ', 1)
            assert auth_mode == 'Basic'
            # Zm9vOmJhcg解碼
            auth_info = base64.b64decode(auth_base64)
            # byte轉str
            auth_username, auth_password = auth_info.decode('utf-8').split(":")
            try:
                name = auth_username
                cursor.execute(
                    "SELECT * FROM blog_bloguser WHERE name='{}'".format(name)
                )
                result = cursor.fetchone()
                if result is not None:
                    password = result['password']
                    if auth_password == password:
                        self.create_auth_header()
                    else:
                        self.create_auth_header()
                else:
                    self.create_auth_header()
            except Exception as e:
                return self.write(e)
        else:
            self.create_auth_header()

發現一個庫,可以很好地封裝

https://pypi.org/project/tornado-basic-auth/

只要在接口上加上裝飾器,裝飾器的入參是一個函數,該函數接收的參數就是basic auth的用戶名,密碼,拿到用戶名後去數據庫裏查一下,函數返回bool類型,True或者False

def basic_auth_valid(user, pwd):

    cursor = mysqldb.cursor(pymysql.cursors.DictCursor)

    try:
        cursor.execute(
            "SELECT * FROM blog_bloguser WHERE name='{}'".format(user)
        )
        result = cursor.fetchone()
        if result is not None:
            password = result['password']
            if pwd == password:
                return True
            else:
                return False
        else:
            return False
    except Exception as e:
        return False


@basic_auth(basic_auth_valid)
class GetALlBlog(tornado.web.RequestHandler):

    def initialize(self, db):
        self.db = db
        print("db is ok")

    def get(self):
        db = self.db
        cursor = db.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute(
                "SELECT A.id, A.title, A.`timestamp`, A.views, A.greats, A.comments,U.name as 'authorname' FROM blog_articles A, blog_bloguser U WHERE A.authorname_id = U.id AND A.STATUS = '有效'LIMIT 10"
            )
            result = cursor.fetchall()
            return_data = {}
            return_data["code"] = 200
            return_data["message"] = "success"
            return_data["data"] = result
            self.finish(json.dumps(return_data, cls=DateEncoder))
        except Exception as e:
            return self.write(e)
        db.commit()
        cursor.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章