本文的内容是个人开源代码(https://github.com/e10101/AdminLogin)的中文说明。
项目主要是实现了经过合理配置Nginx
的auth_request
模块来实现对敏感路径下的内容进行访问限制。javascript
可经过Github访问:https://github.com/e10101/AdminLogin,来获取代码。若是能够的话,能够Star一下。java
这个项目是为了解决网站中部分管理资源(路径)须要进行权限限制,但又不想经过复杂系统去实现而进行编写的项目.nginx
同时这个项目也没有采用Nginx
的auth_basic
模块来实现权限限制.二是经过auth_request
来进行的权限限制.git
本项目是基于NodeJS
/ExpressJS
/PassportJS
以及Github的。github
为讲解方便,假设存在:
服务器A(server1.example.com),其路径/installs
上存有敏感信息,其余路径可公开访问,端口3003。
服务器B(login.example.com),为认证服务器,其上部署了本项目代码,端口4001。浏览器
系统以CentOS
7.2为例,认证使用的Github
用户认证。服务器
服务器A(server1)的Nginx配置文件微信
server { listen 80; listen [::]:80; server_name server1.example.com; location = /auth { internal; proxy_pass http://login.example.com; proxy_pass_request_body off; proxy_set_header X-Original-URI $request_uri; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_page 401 = @error401; location @error401 { return 302 http://login.example.com; } location / { try_files $uri $uri/ @proxy; } # The path has secret content location /installs { auth_request /auth; try_files $uri $uri/ @proxy; } location @proxy { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Host $remote_addr; proxy_pass http://127.0.0.1:3003; } }
服务器B(login)的Nginx配置cookie
server { listen 80; listen [::]:80; server_name login.example.com; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Host $remote_addr; proxy_pass http://127.0.0.1:4001/; } }
用户访问服务器A的敏感资源(即路径/installs
中的内容),Nginx
经过配置文件中的auth_request
字段去请求http://login.example.com/auth,因为用户并未在服务器B进行登陆,所以服务器B返回了401
无权限的错误。session
根据服务器A的配置,发现401
错误后,会向用户返回302
状态指向为服务器B的主机地址(login.example.com)。
用户浏览器跳转到服务器B,并选择第三方的用户认证进行受权(此处以Github为例),当用户经过Github进行受权后,回向服务器B返回用户的我的信息。
服务器B从第三方反馈回的信息中,检索出用户的用户名(username
),而后服务器B会将此用户名与已有的管理员信息进行对比(此处经过配置文件实现),若是登陆用户为合法的管理员帐号,则服务器B受权其登陆进入。若是为非法用户,则不对其受权,所以非法用户没法得到有效登陆凭证。
若是用户为合法用户:
那么服务器B将会生成session,并经过Set-cookie
命令告知用户浏览器。用户经过此Cookie便可得到服务器B的承认受权。当用户经过此Cookie访问服务器B中的/auth
目录时,会返回200
的状态码。
若是用户为非法用户:
那么服务器B将不会session,因为用户没法得到承认的Cookie,那么当用户再次访问/auth
的路径时,服务器会返回401
错误。
假设用户已经受权成功,那么当用户访问服务器A中的敏感内容/installs
时,服务器A访问服务器B的/auth
路径,此时返回200
状态码,服务器A则容许用户进行访问。
以上,经过auth_request
模块以及相关配置就实现了对敏感内容的访问限制。并且经过第三方的机制,也无需本身手工实现登陆功能。同时,此方案能够对同一域名下的不一样子域名中的内容进行访问限制。能够重复利用一个登陆系统,服务于多个其余系统。
设置Express
的session时,因为本案例中使用了不一样的子域名(server1.example.com及login.example.com),须要特别设置cookie
的domain
项,以下所示:
app.use(session({ secret: config.session.secret, cookie: { path: config.cookie.path, domain: config.cookie.domain, maxAge: config.cookie.maxAge } }));
其中的domain格式为:.example.com
。
关于为什么使用Github的问题。
国内能够访问(此项排除了Facebook,Google,Twitter等);
建立应用简单无需审核(此项排除了微信,微博等)。