yeziruo

利欲驱人万火牛 江湖浪迹一沙鸥

一般情况下Nginx自带两个有关于鉴权的模块,一个是auth_basic,另一个是auth_request,本文主要介绍auth_request

流程

21080701.png

Nginx的配置

(server段中,也可以做成一个配置文件,通过include引用)

#设置401错误跳转,用于跳转到登录页
location @error401 {
    #这里的url方便我们登录成功的跳转
    return 302 https://auth.example.com/?url=https://$http_host$request_uri;
}
#内部路由
location /auth {
    internal;
    #鉴权服务器地址
    proxy_pass http://127.0.0.1:8888/auth;
    #不传递body内容,当然请求头会被传递
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
}

(location段中)
location / {
    #指定内部路由与返回401的处理
    auth_request /auth;
    error_page 401 = @error401;
}

鉴权验证

401.jpg
(猫猫来源: https://http.cat/)

Nginx会通过所返回的状态码来判断是否放行请求,返回2XX放行,返回4XX则拦截请求,我们可以通过设置cookie来保证登录态的持续:

(Python3)
from sanic import Sanic, html, json, redirect
app = Sanic(__name__)

password = "19260817"

@app.get("/")
async def index(request):
    return html("<form action="" method="POST"><input name="pw"><button type="submit">check</button></form>")

@app.post("/")
async def vindex(request):
    pw = request.form.get("pw", None)
    url = request.args.get("url", None)
    if pw == password:
        res = redirect(url)
        res.cookies["login"] = True
        res.cookies["login"]["httponly"] = True
        #全域cookie
        res.cookies["login"]["domain"] = ".example.com"
        return res
    return redirect("/")

@app.get("/auth")
async def auth(request):
    login = request.cookies.get("login", False)
    if login:
        return json({"code": 200}, 200)
    return json({"code": 401}, 401)

if __name__ == "__main__":
    app.run(port=8888)

暂无评论

正在回复ID为 ??? 的评论

© 2013-2022 yeziruo. All Rights Reserved. Start5 theme by yeziruo.

CC BY-NC-SA 3.0 CN