重定向前執行js腳本更新requestBody

重定向前執行js腳本更新requestBody

我正在配置 nginx 位置,但我需要運行一個腳本 (njs) 在重定向之前更新 requestBody :

這是我的conf,但是當我部署它時,它仍然重定向而不更新 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

相關內容