1. http_auth_request_module
# 版本说明 nginx 1.20.2, 默认自带 http_auth_request_module
# 模块查看验证 nginx -V (nginx -V| grep 'http_auth_request_module')
2. 鉴权接口准备
- 本文后端接口是通过
Egg.js
来实现的,实现代码取决于项目中使用何种后端语言;
'use strict';
const Controller = require('egg').Controller;
class AuthController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, AuthController';
}
async login() {
const { ctx, service } = this;
const secrect = Date.now();
const jwt_token = await service.actionToken.apply(secrect);
ctx.helper.success();
ctx.body = {
status: 200,
secret: jwt_token,
};
}
async authorize() {
console.log(this.ctx.params);
console.log(this.ctx.query);
const isAuthToken = this.ctx.cookies.get('authorize', {
signed: false,
});
console.log('isAuthToken log', isAuthToken);
console.log('x-original-uri', this.ctx.headers['x-original-uri']);
if (isAuthToken) {
this.ctx.body = {
status: 200,
secret: 'jwt_token',
};
} else {
this.ctx.status = 403;
}
}
}
module.exports = AuthController;
3. 修改Nginx
配置
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location = / {
root index;
index index.html index.htm;
}
location /eggjs {
if ($http_cookie) {
set $code_cookie $http_cookie;
}
if ($arg_code) {
set $code_cookie "authorize=$arg_code; Path=/";
}
# 指定auth_request
auth_request /auth;
proxy_pass http://127.0.0.1:3000/static/index.html;
}
# 验证配置
location /jwt {
proxy_pass http://localhost:3000/authorize;
}
location /scripts {
proxy_pass http://127.0.0.1:3000/static/scripts/;
}
location = /auth {
internal;
# $http_cookie
proxy_set_header Cookie "$code_cookie";
# 鉴权服务器的地址
proxy_pass http://localhost:3000/authorize;
# proxy_pass_request_body off;
# proxy_set_header Content-Length "";
# proxy_set_header X-Original-URI $query_string;
# proxy_set_header X-Original-URI $request_uri;
}
#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 html;
}
}
4. 配置说明
1. 指定auth_request
auth_request /auth;
2. 传递完整的原始请求URI
- 由于身份验证子请求将丢弃请求体,可以通过以下配置传递信息(本文未使用该方式,故皆已注释);
# proxy_pass_request_body off;
# proxy_set_header Content-Length "";
# proxy_set_header X-Original-URI $query_string;
# proxy_set_header X-Original-URI $request_uri;
3. 传递校验信息
# URL: http://localhost:8080/eggjs?code=202304
# 设置变量 $code_cookie,以便后续使用,此处配置兼容 cookie 与 query 两种写法
if ($http_cookie) {
set $code_cookie $http_cookie;
}
if ($arg_code) {
# $arg_code 与 URL上的参数code相对应
# 即 secrect=202304 应对应 $arg_secrect
set $code_cookie "authorize=$arg_code; Path=/";
}
# 在此处使用变量 $code_cookie
proxy_set_header Cookie "$code_cookie";
4. Extra Config Notes
location /eggjs {
auth_request /auth;
auth_request_set $auth_status $upstream_status;
if ($auth_status = "403") {
return 403;
}
proxy_pass http://127.0.0.1:3000/static/index.html;
}