Crossbar wampcra 动态认证

简介: Crossbar wampcra 动态认证

.crossbar 平级目录中添加 authenticator.py 用来操作 crossbar 的认证, 客户端 crossbar 连接输入的用户名密码在这个文件里进行动态认证

from pprint import pprint
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
from autobahn.wamp.exception import ApplicationError
# crossbar "database"
USERDB = {
   'frontend': { # 用户名
      'secret': '123456',  # 密码
      'role': 'frontend' # 角色
   },
   'backend': {
      'authid': 'ID10001',
      'secret': '111111',
      'role': 'backend'
   }
}
class AuthenticatorSession(ApplicationSession):
   @inlineCallbacks
   def onJoin(self, details):
      def authenticate(realm, authid, details):
         print("WAMP-CRA dynamic authenticator invoked: realm='{}', authid='{}'".format(realm, authid))
         if authid in USERDB:
            return USERDB[authid]
         else:
            raise ApplicationError(u'com.example.no_such_user', 'could not authenticate session - no such user {}'.format(authid))
      try:
         yield self.register(authenticate, u'com.example.authenticate')
         print("WAMP-CRA dynamic authenticator registered!")
      except Exception as e:
         print("Failed to register dynamic authenticator: {0}".format(e))

修改 .crossbar 文件夹下的 config.json 文件, 默认是 anonymous 配置,再 roles 节点里面修改,添加 authenticator 认证管理 e.g.

    ...
    "realms": [
                {
                    "name": "realm1",
                    "roles": [
                        {
                            "name": "authenticator",
                            "permissions": [
                                {
                                    "uri": "com.example.authenticate",
                                    "match": "exact",
                                    "allow": {
                                        "call": false,
                                        "register": true,
                                        "publish": false,
                                        "subscribe": false
                                    },
                                    "disclose": {
                                        "caller": false,
                                        "publisher": false
                                    },
                                    "cache": true
                                }
                            ]
                        },
                        {
                            "name": "backend",
                            "permissions": [
                                {
                                    "uri": "",
                                    "match": "prefix",
                                    "allow": {
                                        "call": true,
                                        "register": true,
                                        "publish": true,
                                        "subscribe": true
                                    },
                                    "disclose": {
                                        "caller": false,
                                        "publisher": false
                                    },
                                    "cache": true
                                }
                            ]
                        },
                        {
                            "name": "frontend",
                            "permissions": [
                                {
                                    "uri": "com.example.add2",
                                    "match": "exact",
                                    "allow": {
                                        "call": true,
                                        "register": false,
                                        "publish": false,
                                        "subscribe": false
                                    },
                                    "disclose": {
                                        "caller": false,
                                        "publisher": false
                                    },
                                    "cache": true
                                }
                            ]
                        }
                    ]
                }
            ],
            "transports": [
                {
                    "type": "web",
                    "endpoint": {
                        "type": "tcp",
                        "port": 8080
                    },
                    "paths": {
                        "/": {
                            "type": "static",
                            "directory": "../web"
                        },
                        "ws": {
                            "type": "websocket",
                            "auth": {
                                "wampcra": {
                                    "type": "dynamic",
                                    "authenticator": "com.example.authenticate"
                                }
                            }
                        }
                    }
                }
            ],
            "components": [
                {
                    "type": "class",
                    "classname": "authenticator.AuthenticatorSession",
                    "realm": "realm1",
                    "role": "authenticator"
                }
            ]
           ...

"name": "backend" 角色为后端,配置权限 "match": "prefix" 设置 uri 的匹配规则。 prefix matching 前缀匹配

{
    "name": "backend",
    "permissions": [
        {
            "uri": "",
            "match": "prefix",
            "allow": {
                "call": true,
                "register": true,
                "publish": true,
                "subscribe": true
            },
            "disclose": {
                "caller": false,
                "publisher": false
            },
            "cache": true
        }
    ]
}

设置 websocket 认证方式, auth 中配置 wampcra 模式,类型为 dynamic

"ws": {
    "type": "websocket",
    "auth": {
        "wampcra": {
            "type": "dynamic",
            "authenticator": "com.example.authenticate"
        }
    }
}

"name" : "authenticator" 启动crossbar 挂载的 component

"components": [
    {
        "type": "class",
        "classname": "authenticator.AuthenticatorSession",
        "realm": "realm1",
        "role": "authenticator"
    }
]

crossbar 客户端连接添加user和key backend 角色 python 例子 e.g.

import os
import sys
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
from autobahn.wamp.types import PublishOptions
from autobahn.wamp import auth
USER = u'backend'
USER_SECRET = u'111111'
class ClientSession(ApplicationSession):
   def onConnect(self):
      self.join(self.config.realm, [u"wampcra"], USER)
   def onChallenge(self, challenge):
      if challenge.method == u"wampcra":
         if u'salt' in challenge.extra:
            key = auth.derive_key(USER_SECRET,
                                  challenge.extra['salt'],
                                  challenge.extra['iterations'],
                                  challenge.extra['keylen'])
         else:
            key = USER_SECRET
         signature = auth.compute_wcs(key, challenge.extra['challenge'])
         return signature
      else:
         raise Exception("Invalid authmethod {}".format(challenge.method))
   @inlineCallbacks
   def onJoin(self, details):
      def add2(x, y):
         print("add2() called with {} and {}".format(x, y))
         return x + y
      try:
         reg = yield self.register(add2, u'com.example.add2')
         print("procedure add2() registered")
      except Exception as e:
         print("could not register procedure: {}".format(e))
      try:
         reg = yield self.register(add2, u'com.example.wewobackend.test')
         print("wewobackend.test registered")
      except Exception as e:
         print("wewobackend.test could not register procedure: {}".format(e))
   def onLeave(self, details):
      print("Client session left: {}".format(details))
      self.disconnect()
   def onDisconnect(self):
      reactor.stop()
if __name__ == '__main__':
   from autobahn.twisted.wamp import ApplicationRunner
   runner = ApplicationRunner(url=u'ws://localhost:8080/ws', realm=u'realm1')
   runner.run(ClientSession)


目录
相关文章
|
Linux
LINUX使用sig文件验证文件的签名
LINUX使用sig文件验证文件的签名
1355 0
|
19天前
|
存储 弹性计算 人工智能
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
2025年9月24日,阿里云弹性计算团队多位产品、技术专家及服务器团队技术专家共同在【2025云栖大会】现场带来了《通用计算产品发布与行业实践》的专场论坛,本论坛聚焦弹性计算多款通用算力产品发布。同时,ECS云服务器安全能力、资源售卖模式、计算AI助手等用户体验关键环节也宣布升级,让用云更简单、更智能。海尔三翼鸟云服务负责人刘建锋先生作为特邀嘉宾,莅临现场分享了关于阿里云ECS g9i推动AIoT平台的场景落地实践。
【2025云栖精华内容】 打造持续领先,全球覆盖的澎湃算力底座——通用计算产品发布与行业实践专场回顾
|
10天前
|
云安全 人工智能 安全
Dify平台集成阿里云AI安全护栏,构建AI Runtime安全防线
阿里云 AI 安全护栏加入Dify平台,打造可信赖的 AI
|
13天前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
1113 40
|
13天前
|
机器学习/深度学习 人工智能 搜索推荐
万字长文深度解析最新Deep Research技术:前沿架构、核心技术与未来展望
近期发生了什么自 2025 年 2 月 OpenAI 正式发布Deep Research以来,深度研究/深度搜索(Deep Research / Deep Search)正在成为信息检索与知识工作的全新范式:系统以多步推理驱动大规模联网检索、跨源证据。
888 57
|
10天前
|
文字识别 测试技术 开发者
Qwen3-VL新成员 2B、32B来啦!更适合开发者体质
Qwen3-VL家族重磅推出2B与32B双版本,轻量高效与超强推理兼备,一模型通吃多模态与纯文本任务!
733 11
|
4天前
|
人工智能 数据可视化 Java
Spring AI Alibaba、Dify、LangGraph 与 LangChain 综合对比分析报告
本报告对比Spring AI Alibaba、Dify、LangGraph与LangChain四大AI开发框架,涵盖架构、性能、生态及适用场景。数据截至2025年10月,基于公开资料分析,实际发展可能随技术演进调整。
323 4