Nginx + Flask搭建LDAP认证--nginx-auth-request-module 的使用

本文介绍了如何利用Nginx的auth_request模块和Flask搭建LDAP认证系统,解决Kibana、Elasticsearch等应用的授权问题。通过自定义服务,根据返回状态码决定是否允许访问,实现安全的内部应用访问控制。详细步骤包括Nginx的重新编译和配置,以及Flask应用的结构和功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Nginx + Flask搭建LDAP认证--nginx-auth-request-module 的使用

需求由来

kibana,Elasticsearch 等业务需要对外服务的时候,头痛了把。传统方法 使用basic认真。用户管理起来麻烦。

公司内部有多个业务开发部门,为了保证这些员工能正常访问 内部一些无法提供认证服务的应用兼顾到系统安全。通过nginx-auth-request-module来实现认证转移。

参考

https://www.cnblogs.com/vipzhou/p/8420808.html
https://github.com/perusio/nginx-auth-request-module
https://www.jianshu.com/p/9f2da3cf5579 (大思路)

Nginx 的 auth_request 模块

auth_request 大抵就是在你访问 Nginx 中受 auth_reuqest 保护的路径时,去请求一个特定的服务。根据这个服务返回的状态码,auth_request 模块再进行下一步的动作,允许访问或者重定向跳走什么的。因此我们可以在上面去定制我们所有个性化的需求。

假定我们的环境是 centos ,yum 安装 nginx 就略了。由于通过 yum 等安装的 nginx 默认没有编译 auth_request 模块。我们需要重新编译一下。

先运行 nginx -V 来获取当前 nginx 的编译参数

nginx安装

本例子,以centos 7.6

yum install epel-release -y
yum install nginx

nginx -V 确认是否带有auth_request模块

[root@vm188-ai ~]# nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-stream_ssl_preread_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-http_auth_request_module --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

Nginx 认证

主要利用nginx-auth-request-module 进行鉴权

- 1、auth_request对应的路由返回401 or 403时,会拦截请求直接nginx返回前台401 or 403信息;
- 2、auth_request对应的路由返回2xx状态码时,不会拦截请求,而是构建一个subrequest请求再去请求真实受保护资源的接口;
graph LR
a[client]-->B[NGINX plus]
B-->c[backend]
c-->B
B-->D(ldap_auth daemon)
D-->E(ldap server)
E-->D
D-->B


graph TB
a[用户请求]-->B[nginx转发请求ldap]
B-->c[LDAP 401]
c-->d[后端发送登录表单]
d-->e[用户提交认证信息]
e-->f[nginx转发cookie给ldap_auth]
f-->g[ldap_auth请求ldap认证]
g-->h{认证成功}
h-.no.->c
h-.yes.->C[LDAP 200]
C-->END

1. 客户端发送 HTTP 请求,以获取 Nginx 上反向代理的受保护资源。

2. Nginx 的 auth_request 模块 将请求转发给 ldap-auth 这个服务(对应 nginx-ldap-auth-daemon.py),首次肯定会给个 401 .

3. Nginx 将请求转发给 http://backend/login,后者对应于这里的后端服务。它将原始请求的 uri 写入X-Target ,以便于后面跳转。

4. 后端服务向客户端发送登录表单(表单在 demo 代码中定义)。根据 error_page 的配置,Nginx 将登录表单的 http 状态码返回 200。

5. 用户填写表单上的用户名和密码字段并单击登录按钮,从向 / login 发起 POST 请求,Nginx 将其转发到后端的服务上。

6. 后端服务把用户名密码以 base64 方式写入 cookie。

7. 客户端重新发送其原始请求(来自步骤1),现在有 cookie 了 。Nginx 将请求转发给 ldap-auth 服务(如步骤2所示)。

8. ldap-auth 服务解码 cookie,然后做 LDAP 认证。

9. 下一个操作取决于 LDAP 认证是否成功

/etc/nginx/conf.d/auth.conf

proxy_cache_path cache/  keys_zone=auth_cache:10m;
server {
   
   
        listen       80;
        server_name  xxx.xxx.xxx.xxx;

        location / {
   
   
            auth_request /auth;
            error_page 401 = @error401;
            set $mysitename 'ES1 warehouse staff';   # 自定义变量
            auth_request_set $user $upstream_http_x_forwarded_user;
            proxy_set_header X-Forwarded-User $user;
           root /var/www/html;
            proxy_pass http://xxx.xxx.xxx.xxx:33307;   # 认证后目标服务器
            allow 192.168.0.0/16;  # 增加白名单
            allow 10.0.0.0/8;
            deny all;
        }


        location @error401 {
   
   
             add_header Set-Cookie "NSREDIRECT=$scheme://$http_host$request_uri;Path=/";
             add_header Set-Cookie "NSREDIRECTSITENAME=$mysitename";
              return 302  /login;
        }

       location /login {
   
   
          proxy_pass http://127.0.0.1:8001/login;
        }

    	location /logout {
   
   
    	    proxy_pass http://127.0.0.1:8001/logout;
    	    }
        location /auth {
   
   
          internal;
            proxy_pass http://127.0.0.1:8001/auth;
            proxy_set_header Host $host;
            proxy_pass_request_body off;
            proxy_set_header Content-Length "";
        }
      location /static {
   
    proxy_pass http://127.0.0.1:8001/static;}
      location /captcha {
   
    proxy_pass http://127.0.0.1:8001/captcha;}


}

Flask

目录架构

.
├── app.py
├── config.py
├── mycaptcha.py
├── run.py
├── static
│   ├── captcha
│   ├── favicon.ico
│   ├── images
│   │   ├── avatar.png
│   │   ├── bg.svg
│   │   ├── login-bg.jpg
│   │   ├── loginbg.jpg
│   │   └── logo.png
│   ├── js
│   │   ├── jquery-3.3.1.min.js
│   │   ├── main.js
│   │   └── template-web.js
│   └── style
│       └── style.css
├── templates
│   └── login.html
└── views.py

run.py

#!`which python`

from app import app

app.run(host='0.0.0.0',port=8001)

app.py

# coding: utf-8
import json

from flask import Flask, url_for, request, session, make_response, abort
from flask_ldap3_login import LDAP3LoginManager
from flask_login import LoginManager, login_user, UserMixin, current_user, logout_user, login_required
from flask import render_template_string, redirect, render_template, flash, get_flashed_messages
from flask_ldap3_login.forms import LDAPLoginForm
import re
import ldap3
from config import *

import string, random, time
from mycaptcha import Captcha
import os
from datetime import timedelta
import hashlib

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True

# Setup LDAP Configuration Variables. Change these to your own settings.
# All configuration directives can be found in the documentation.


# session
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=30)

# Hostname of your LDAP Server
app.config['LDAP_HOST'] = LDAPURL

# Base DN of your directory
app.config['LDAP_BASE_DN'] = 'dc=xxx,dc=cn'

# Users DN to be prepended to the Base DN
app.config['LDAP_USER_DN'] = 'ou=staff'

# Groups DN to be prepended to the Base DN
app.config['LDAP_GROUP_DN'] = 'ou=g'

# The RDN attribute for your user schema on LDAP
app.config['LDAP_USER_RDN_ATTR'] = 'cn'

# The Attribute you want users to
<think>好的,我现在需要处理用户关于ITSM自动化运维平台搭建的保姆级教程请求。首先,回顾之前的对话历史,用户之前询问了自动生成工单的运维软件部署,我给出了详细的指南,包括工具选型、部署架构、流程、安全措施等。现在用户进一步要求更全面的ITSM平台搭建教程,可能需要涵盖更广泛的内容,比如IT服务管理的各个方面,而不仅仅是工单生成。 用户可能希望得到一个从零开始的详细步骤,适合没有太多经验的人跟随操作。考虑到用户之前的问题,他们可能对开源的工具有兴趣,比如Zammad、Zabbix等,所以教程可能需要推荐开源或免费的工具,同时可能涉及企业级解决方案。 我需要确定用户的使用场景,可能是企业内部的运维团队,或者是中小型公司希望自动化他们的IT服务管理流程。用户可能是IT运维人员、系统管理员或技术负责人,需要搭建一个完整的ITSM平台,包括事件管理、变更管理、资产管理等模块。 用户的真实需求不仅仅是步骤,还包括最佳实践、常见问题解决和优化建议。他们可能需要详细的配置示例、代码片段、架构图以及如何整合不同工具。此外,用户可能对成本、安全性和扩展性有顾虑,所以教程需要涵盖这些方面。 接下来,我需要组织一个结构清晰的保姆级教程,分步骤讲解,确保每个环节都有详细的操作指南。可能的结构包括:环境准备、核心组件安装、基础配置、自动化规则设置、与其他系统集成、安全加固、维护优化等。需要包含具体的命令、配置文件示例、流程图以及验证方法。 同时,要考虑到用户可能遇到的问题,比如依赖项安装失败、服务无法启动、API接口不通等,提供排查步骤和解决方案。此外,可能需要比较不同工具的优势和适用场景,帮助用户根据自身情况选择。 另外,用户之前得到的内容中使用了Mermaid图表和数学公式,这次可能需要延续这种风格,但要注意是否符合他们的Markdown渲染环境。如果用户无法显示Mermaid,可能需要改用其他方式呈现架构图,比如文本图表或图片链接。 最后,确保语言简洁明了,步骤详细但不过于冗长,关键配置和代码突出显示,方便用户复制粘贴。同时,提供参考资料和进一步学习的资源,帮助用户深入理解。</think>--- ### ITSM自动化运维平台搭建保姆级教程 --- #### 一、环境准备(以CentOS 7为例) **1. 基础要求** ```bash # 验证系统环境 $ cat /etc/redhat-release # 确认系统版本 $ free -h # 内存≥4GB $ df -h / # 磁盘≥50GB ``` **2. 依赖安装** ```bash # 安装基础工具链 sudo yum install -y epel-release sudo yum install -y docker git python3-pip nginx sudo systemctl start docker && sudo systemctl enable docker ``` --- #### 二、核心组件部署 **1. 服务台系统(ITSM核心)** ```bash # 使用iTop社区版(开源) docker run -d --name itop \ -p 8080:80 \ -v itop-data:/var/www/html \ -e MYSQL_ROOT_PASSWORD=your_password \ combodo/itop:latest ``` **验证安装**:访问 `http://服务器IP:8080`,完成初始化配置 **2. 监控系统(Prometheus+Grafana)** ```yaml # docker-compose.yml version: '3' services: prometheus: image: prom/prometheus ports: - "9090:9090" grafana: image: grafana/grafana ports: - "3000:3000" ``` ```bash $ docker-compose up -d ``` **3. 自动化引擎(Ansible Tower)** ```bash # 使用官方安装包 wget https://releases.ansible.com/ansible-tower/setup/ansible-tower-setup-latest.tar.gz tar xvf ansible-tower-setup-latest.tar.gz cd ansible-tower-setup-*/ # 修改inventory文件后执行 $ sudo ./setup.sh ``` --- #### 三、基础配置流程 **1. 服务目录配置** ```sql -- 创建服务目录表 CREATE TABLE service_catalog ( id INT PRIMARY KEY AUTO_INCREMENT, service_name VARCHAR(50) NOT NULL, sla_level ENUM('黄金', '白银', '青铜') DEFAULT '青铜', owner_team VARCHAR(30) ); INSERT INTO service_catalog VALUES (1, '服务器运维', '黄金', '基础架构组'), (2, '应用支持', '白银', '应用运维组'); ``` **2. 工单流程设计** ```mermaid $$ \begin{array}{cccccc} \text{新建} & \rightarrow & \text{处理中} & \rightarrow & \text{待验证} & \rightarrow & \text{已解决} \\ \uparrow & & \downarrow_{\text{需补充}} & & \downarrow_{\text{驳回}} \\ \text{已关闭} & \leftarrow & \text{复核通过} & \leftarrow & \text{验证中} \\ \end{array} $$ ``` **3. 服务级别协议(SLA)** $$ \text{响应时间} = \begin{cases} 15\text{分钟} & \text{黄金级} \\ 1\text{小时} & \text{白银级} \\ 4\text{小时} & \text{青铜级} \end{cases} $$ --- #### 四、自动化集成配置 **1. 告警自动生成工单(Prometheus → iTop)** ```yaml # prometheus告警规则示例 groups: - name: host-alert rules: - alert: HighCPUUsage expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80 for: 5m labels: severity: critical annotations: description: 'CPU使用率超过80%: {{ $value }}%' ``` **2. 自动化处理配置(iTop → Ansible)** ```python # iTop webhook处理脚本示例 import requests from flask import Flask, request app = Flask(__name__) @app.route('/webhook', methods=['POST']) def handle_webhook(): data = request.json if data['priority'] == '紧急': requests.post('https://ansible/api/v2/job_templates/7/launch/', headers={'Authorization': 'Bearer your_token'}, json={"extra_vars": {"host": data['host']}}) return 'Received', 200 ``` --- #### 五、权限管理体系 **1. RBAC角色配置** ```yaml # 角色权限矩阵示例 roles: - name: 运维工程师 permissions: - ticket_create - ticket_edit - server_restart - name: 服务台人员 permissions: - ticket_view - ticket_assign ``` **2. LDAP集成(对接AD域)** ```properties # iTop配置文件修改 'allowed_login_types' => 'form,external', 'auth_remote' => true, 'auth_remote_user_autologin' => true, 'auth_remote_header_name' => 'AUTH_USER', ``` --- #### 六、数据可视化配置 **1. Grafana仪表盘示例** ```sql -- SLA达成率计算公式 SELECT (COUNT(CASE WHEN resolved_time <= sla_due THEN 1 END) * 100.0) / COUNT(*) FROM tickets WHERE create_time BETWEEN '${__from:date}' AND '${__to:date}' ``` **2. 资源利用率看板** $$ \text{健康度评分} = 0.4 \times \text{CPU使用率} + 0.3 \times \text{内存使用率} + 0.3 \times \text{磁盘使用率} $$ --- #### 七、灾备方案设计 **1. 数据库主从同步** ```bash # MySQL主库配置 [mysqld] server-id=1 log-bin=mysql-bin # 从库配置 [mysqld] server-id=2 relay-log=mysql-relay-bin read-only=1 ``` **2. 定时备份脚本** ```bash #!/bin/bash mysqldump -u root -p$DB_PASS itop | gzip > /backup/itop_$(date +%F).sql.gz find /backup -name "*.sql.gz" -mtime +30 -delete ``` --- #### 八、常见问题排查指南 | 问题现象 | 排查命令 | 解决方案 | |---------|----------|----------| | 服务无法启动 | `journalctl -u docker --since "5 minutes ago"` | 检查端口冲突或存储卷权限 | | API调用失败 | `tcpdump -i eth0 port 443 -w api.pcap` | 检查SSL证书和防火墙规则 | | 工单同步延迟 | `show processlist;` | 优化数据库索引:<br>`CREATE INDEX idx_ticket_status ON tickets(status)` | --- #### 九、优化建议 1. **自动化分级实施**: $$ \text{成熟度模型} = \begin{cases} \text{Level1: 手工处理} \\ \text{Level2: 条件触发} \\ \text{Level3: AI预测} \end{cases} $$ 2. **容量规划公式**: $$ \text{所需人力} = \frac{\text{日均工单量} \times \text{平均处理时长}}{8\text{小时}} \times 1.2 $$ --- #### 十、学习资源推荐 1. **官方文档**: - [iTop配置手册](https://www.itophub.io) - [Ansible Tower API指南](https://docs.ansible.com) 2. **书籍推荐**: - 《IT服务管理标准指南(ITIL 4)》 - 《自动化运维:从零构建企业级平台》 --- 通过以上步骤可实现从零搭建完整的ITSM自动化运维平台。建议按以下阶段推进: 1. **基础搭建**:完成核心组件安装(1-2天) 2. **流程验证**:测试工单全生命周期流转(3-5天) 3. **自动化扩展**:逐步添加智能分析模块(持续迭代) 部署过程中如遇问题,可优先检查各组件日志文件(路径参考): - iTop日志:`/var/www/html/log/error.log` - Prometheus日志:`docker logs prometheus`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值