sanic路由的基本、摘要和承载令牌认证
Sanic-HTTPAuth的Python项目详细描述
Sanic HttpAuth
这是萨尼克的Flask-HTTPAuth叉子。它是一个简单的扩展,为sanic路由提供基本和摘要http身份验证。
仍在进行中的工作,欢迎作出贡献。
安装
最简单的安装方法是通过pip。
pip install Sanic-HTTPAuth
基本身份验证示例
importhashlibfromsanicimportSanicfromsanic_httpauthimportHTTPBasicAuthapp=Sanic(__name__)auth=HTTPBasicAuth()defhash_password(salt,password):salted=password+saltreturnhashlib.sha512(salted.encode("utf8")).hexdigest()app_salt="APP_SECRET - don't do this in production"users={"john":hash_password(app_salt,"hello"),"susan":hash_password(app_salt,"bye"),}@auth.verify_passworddefverify_password(username,password):ifusernameinusers:returnusers.get(username)==hash_password(app_salt,password)returnFalse@app.route("/")@auth.login_requireddefindex(request):return"Hello, %s!"%auth.username()if__name__=="__main__":app.run()
注意:请参阅Flask-HTTPAuth documentation以获取涉及密码散列和自定义验证回调的更复杂示例。
摘要式身份验证示例
fromsanicimportSanicfromsanic_httpauthimportHTTPDigestAuthfromsanic_sessionimportSessionapp=Sanic(__name__)app.config["SECRET_KEY"]="secret key here"auth=HTTPDigestAuth()Session(app)users={"john":"hello","susan":"bye"}@auth.get_passworddefget_pw(username):ifusernameinusers:returnusers.get(username)returnNone@app.route("/")@auth.login_requireddefindex(request):return"Hello, %s!"%auth.username()if__name__=="__main__":app.run()