NGINX身份验证请求

时间:2020-04-05 11:53:29

标签: nginx flask auth-request

我目前使用nginx作为网络中多个不同Web服务器的反向代理。到目前为止,我只是成功地使用了basic_auth,但想对其进行改进。我正在尝试将auth_request和Flask Mega Tutorial组合在一起以创建身份验证门户。

我有两条烧瓶路线,一条检查用户是否已经登录并返回200,否则返回401。

@app.route('/nzb_auth', methods=['GET', 'POST'])
def nzb_auth():
    if current_user.is_authenticated:
        return Response(status=200)

nginx捕获401并重定向到我的/ login页面。登录页面进行身份验证,一旦成功,将向nginx返回200。

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return Response(status=200)
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return Response(status=200)
    return render_template('login.html', title='Sign In', form=form)

似乎非常接近工作,但还远远不够。当我到达www.example.com站点时,可以看到nginx成功执行/ auth后,发现我没有登录,然后重定向到/ login。但是,成功登录后,我被带到一个空白页面。根据地址栏,我仍在/ login。

起初,我认为它根本不起作用,但是为了进行测试,我在'/'上向我的内部站点之一添加了proxy_pass并再次尝试。仍然没有运气。但是偶然地,我在同一个“私有窗口”中再次打开了www.example.com,它确实起作用了!

因此,似乎每个步骤都成功,一旦auth_request最初成功,我就不会被重定向到任何地方。有什么建议?这是我的服务器块(我删除了该代理密码)。

server {
    root /var/www/[SERVER DIRECTORY]/html;
    index index.html index.htm index.nginx-debian.html;
    server_name [SERVER NAME];

    location / {
        auth_request    /nzb_auth;
        error_page 401 = @error401;
    }
    #If user is logged in, 200 gets returned, otherwise 401
    location = /nzb_auth {
        internal;
        proxy_pass  [http://SERVER NAME]/nzb_auth;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header        X-Original-URI $request_uri;
    }
    #login route for nzb_auth
    location /login {
        proxy_pass [http://SERVER NAME]/login;
        proxy_set_header        X-Original-URI $request_uri;
    }
    #If not logged in /nzb_auth responds with 401, nginx redirects to /login
    location @error401 {
        return 302 [http://SERVER NAME]/login;
}
}
    return Response(status=401)

0 个答案:

没有答案