【问题标题】:Prevent cross domain websocket request防止跨域 websocket 请求
【发布时间】:2018-04-06 16:54:37
【问题描述】:

我的 web 应用程序有一个 websocket 服务器,网址为:http://example.com:8080,当我在服务器上运行它时,它适用于我的域 http://anotherdomain.com,但它也适用于其他域 http://baddomain.com 我想要的是阻止其他域访问我的 websocket,即我希望只有我的域可以访问我的 websocket 我该怎么办?

我正在使用 nodejs 的 ws 模块 (https://github.com/websockets/ws)

const WebSocket = require('ws')
const wss = new WebSocket.Server({port:8080})

wss.on('connection', ws => {
    ws.on('message', data => {
        // something here
    })
})

【问题讨论】:

    标签: node.js websocket


    【解决方案1】:

    一种方法是检查 IP。 您可以从传递给 on.connection 事件的请求对象中获取它。

    wss.on('connection', (ws, req) => {
        ws.on('message', data => {
            let _thisIP = req.connection.localAddress; //you can compare it now
        })
    })
    

    【讨论】:

    • 我得到了地址!太棒了,tysm
    猜你喜欢
    • 1970-01-01
    • 2013-12-23
    • 2011-09-27
    • 2012-04-18
    • 2019-11-04
    • 2017-02-06
    • 2021-06-26
    相关资源
    最近更新 更多