Sah*_*Ali 7 javascript node.js cors express microservices
我一直绞尽脑汁寻求一个简单的解决方案.可以说,我的Node JS应用程序中有10个API端点.
我已经允许其中3个公开,其余4个具有基于JWT的身份验证
现在我还有3个路由,它们没有JWT,我只需要允许服务器端调用.没有浏览器或卷发或邮递员,应该可以打电话给他们.如何从请求对象中识别出它来自服务器?
或者换句话说,如何拒绝所有对我的api的跨源调用?由于服务器端不属于CORS,因此它们应该过滤掉
您可以使用express-ipfilter包并将其仅应用于您要保护的某些路由:
const express = require('express'),
ipfilter = require('express-ipfilter').IpFilter;
// Whitelist the following IPs
const ips = ['127.0.0.1'];
// Create the route
app.get("/securePath", ipfilter(ips, {mode: 'allow'}), (req, res) => {
// only requests from 127.0.0.1 (localhost/loopback) can get here
});
app.get("/openPath", (req, res) => {
// all requests can get here
});
app.listen(3000);
Run Code Online (Sandbox Code Playgroud)
如果您在代理后面使用 Node,则可能需要配置代理以使用实际 IP 设置标头,然后将属性中的ipfilter函数传递detectIp给第二个参数。
假设您正在使用 nginx 并将其配置为通过x-Real-IP标头发送原始 IP ,您可以将此函数传递给ipfilter:
const express = require('express'),
ipfilter = require('express-ipfilter').IpFilter,
ips = ['127.0.0.1'];
app.get("/securePath", ipfilter(ips, {mode: 'allow', detectIp: getIp}), (req, res) => {
// only requests from 127.0.0.1 (localhost/loopback) that go through the proxy can get here.
});
app.get("/openPath", (req, res) => {
// all requests can get here
});
app.listen(3000);
function getIp(req) { return req.headers["X-Real-IP"] }
Run Code Online (Sandbox Code Playgroud)
对于从客户端进行 JWT 身份验证的路由,您应该使用类似的身份验证/授权。
这意味着调用方服务还应该使用 JWT 令牌进行身份验证,具有特殊role的service或类似的东西(这是您选择的约定的 100% 决定)。该令牌应由调用者签名并由接收微服务验证。
该解决方案的优点是不依赖于基础设施,无论服务部署在哪里,它的工作方式都是一样的。
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |