nginx-auth-request-modulehtml
该模块是nginx一个安装模块,使用配置都比较简单,只要做用是实现权限控制拦截做用。默认高版本nginx(好比1.12)已经默认安装该模块,下面介绍下使用该模块实现多个站点之间的统一权限控制。nginx
这里用一个例子来讲明下,以下例子是包含site1(对应web1)、site2(对应web2)、auth(20.131:7001)在内的三个应用项目,auth项目主要作权限拦截,好比jwt校验等,site一、site2分别为两个受保护的资源站点,只有auth受权经过后才能访问该站点。web
实现上述要求nginx配置详情以下(nginx地址为20.198):api
upstream web1 { server 192.168.20.131:3000; } upstream web2 { server 192.168.20.131:3001; } server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/host.access.log main; location / { root /usr/share/nginx/html; index index.html index.htm; } location /api/web1 { auth_request /auth; error_page 401 = @error401; auth_request_set $user $upstream_http_x_forwarded_user; proxy_set_header X-Forwarded-User $user; proxy_pass http://web1; } location /api/web2 { auth_request /auth; error_page 401 = @error401; auth_request_set $user $upstream_http_x_forwarded_user; proxy_set_header X-Forwarded-User $user; proxy_pass http://web2; } location /auth { internal; proxy_set_header Host $host; proxy_pass_request_body off; proxy_set_header Content-Length ""; proxy_pass http://192.168.20.131:7001/auth; } location @error401 { add_header Set-Cookie "NSREDIRECT=$scheme://$http_host$request_uri;Path=/"; return 302 http://192.168.20.131:7001/login; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
配置好以后,要明白一点,那就是nginx-auth-request-module模块基本使用原理就是:浏览器
一、auth_request对应的路由返回401 or 403时,会拦截请求直接nginx返回前台401 or 403信息;
二、auth_request对应的路由返回2xx状态码时,不会拦截请求,而是构建一个subrequest请求再去请求真实受保护资源的接口;async
因此,基于此,auth模块只须要校验而后返回相应的状态码便可实现权限拦截操做,简单测试以下:测试
auth代码:this
// 受权认证接口 async auth() { console.log(Date.now()); this.ctx.status = 200; } // 失败后的登陆页面 async login() { console.log('失败了........'); this.ctx.body = { msg: '受权失败', code: 10001 } }
这里的auth受权接口咱们直接返回200,login是上述auth项目下配置的路由,用于受权失败后302至登陆页面用的。code
site1和site2代码相同,只罗列一个以下:router
/* /api/web1/users,若是是web2则为/api/web2/users */ router.all('/', function(req, res, next) { res.send('respond with a resource from web1'); });
这里只是简单渲染输出一个字符串而已,测试以下:
浏览器访问:http://192.168.20.198/api/web1/users,输出:
改变auth接口以下:
// 受权认证接口 async auth() { console.log(Date.now()); this.ctx.status = 401; } // 失败后的登陆页面 async login() { console.log('失败了........'); this.ctx.body = { msg: '受权失败', code: 10001 } }
这里将状态码改成了401,再次访问:http://192.168.20.198/api/web1/users,输出:
这里能够看到,浏览器直接进行了302跳转,由于鉴权失败,直接重定向到登陆页面了。
以上就是关于nginx-auth-request-module模块的基本操做及配置,多个项目下部署统一的权限接口时仍是至关有用的。