You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为RPyC服务器实现用户名密码身份验证

RPyC的用户名密码认证采用挑战-应答机制完成身份校验,密码本身不会以明文形式在网络中传输,完整的传递和校验流程如下:

  • 客户端发起连接请求时,首先向服务端提交用户名
  • 服务端匹配到对应用户的存储密码后,生成一个随机的一次性挑战字符串返回给客户端
  • 客户端本地使用该挑战字符串 + 本地密码做哈希运算,将哈希结果返回给服务端
  • 服务端使用相同的挑战字符串 + 存储的对应用户密码做相同哈希运算,两次结果一致则允许建立连接,否则抛出AuthenticationError拒绝连接

完整实现示例

服务端实现

import rpyc
from rpyc.utils.authenticators import SignatureAuthenticator
from rpyc.utils.server import ThreadedServer

# 配置用户名-密码映射表,生产环境建议加密存储不要明文写在代码中
USER_CRED = {
    "user1": b"your_secure_password_1",
    "user2": b"your_secure_password_2"
}

def password_lookup(username):
    """根据用户名返回对应密码,查询不到返回None即可触发认证失败"""
    return USER_CRED.get(username.decode("utf-8"))

# 实例化认证器,传入密码查询函数
authenticator = SignatureAuthenticator(password_lookup)

# 自定义服务类
class DemoService(rpyc.Service):
    def exposed_get_info(self):
        return "认证成功,已访问受保护接口"

if __name__ == "__main__":
    server = ThreadedServer(
        DemoService,
        port=18812,
        authenticator=authenticator,
        hostname="0.0.0.0"
    )
    server.start()

客户端实现

import rpyc

# 连接时传入用户名和密码参数即可
conn = rpyc.connect(
    "127.0.0.1",
    18812,
    username="user1",
    password=b"your_secure_password_1"
)

# 调用服务端接口
print(conn.root.get_info())

可选扩展

如果需要自定义认证逻辑(比如调整哈希算法、添加登录日志、限制IP等),可以继承SignatureAuthenticator类重写对应的认证方法即可。

内容的提问来源于stack exchange,提问作者m0hithreddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:06:03