
nginx の場所を設定していますが、リダイレクト前に requestBody を更新するスクリプト (njs) を実行する必要があります。
これは私の設定ですが、デプロイすると、requestBody を更新せずにリダイレクトしたり、エラーを返したりします。
親 nginx.conf:
// .....
js_import checkScript from /etc/nginx/js/scripts/checkScript.js;
// ....
checkScript.js の場合:
export default {
rights
}
function rights(r) {
const body = JSON.parse(r.requestBody);
if (body.isAdmin) {
body.rights = ['ADMIN'];
r.requestBody = JSON.stringify(body);
} else {
r.return(403, 'Not admin');
}
}
製品.http-service.conf:
location /api/data/products/new {
set $gateway_role "dev.yumStore";
set $gateway_realm "yumStore";
auth_request /_tokenExchange;
# check rights and update body
js_content checkScript.rights;
proxy_set_header "Authorization" $gateway_auth_header;
# redirection
proxy_pass $OUTGATEWAY/api/data/products/new;
}
手伝ってくれてありがとう!!
答え1
関数内の JSON ドキュメントのローカル コピーを更新しています。
これが許可されているかどうかはわかりませんが、試すことができます:
function rights(r) {
const body = JSON.parse(r.requestBody);
if (body.isAdmin) {
body.rights = ['ADMIN']
r.requestBody = JSON.stringify(body); // I don't know if nginx JS allows overwriting the requestBody...
} else {
r.return(403, 'Not admin');
}
}
このアプローチは簡単に回避できるため、これに加えて管理者部分に適切な認証があることを願います。
答え2
本文をdetrevni
nginx に送信するとします。これは、文字列を に変換する njs モジュールでinverted
、 proxy_pass を上流サーバーに送信し、上流サーバーは で応答しますechoing: inverted
。
次の設定は上記のテストで機能します。お役に立てば幸いです。
デフォルト.conf:
js_import main from invert.js;
server {
location /ping {
return 200 'pong';
}
location / {
js_content main.invert;
}
location /api {
proxy_pass http://host.docker.internal:5015;
}
}
反転.js
async function invert(r) {
let body = r.requestText;
let inverted = body.split("").reverse().join("");
let res = await r.subrequest("/api", { body: inverted });
r.return(res.status, res.responseBody);
}
export default { invert };
アピ
const server = new Server(5015, async (request, response) => {
const incoming = await payload(request);
const answer = `echoing: ${incoming}`;
console.log("answering with", answer);
response.writeHead(200, { "content-type": "text/plain" });
response.write(answer);
response.end();
});
コードはここにあります:https://github.com/ericminio/learning-nginx/tree/master/njs-modify-body