第12章 插件与扩展机制
12.1 插件架构
Mosquitto Core
插件接口
认证插件
ACL插件
消息处理插件
外部认证
动态权限
消息增强
12.2 认证插件
动态认证流程
数据库 认证插件 Mosquitto 客户端 数据库 认证插件 Mosquitto 客户端 CONNECT 请求认证 查询用户 返回密码hash 验证密码 认证结果 CONNACK
配置示例
bash
# /etc/mosquitto/mosquitto.conf
# 加载认证插件
plugin /usr/lib/mosquitto/auth_plugin.so
# 配置数据库
auth_opt_db_host localhost
auth_opt_db_port 3306
auth_opt_db_name mqtt
auth_opt_db_user mqtt_user
auth_opt_db_password mqtt_pass
12.3 自定义插件开发
插件结构
c
#include <mosquitto_plugin.h>
int mosquitto_auth_plugin_version(void) {
return MOSQUITTO_AUTH_PLUGIN_VERSION;
}
int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *opts, int opt_count) {
// 初始化插件
return MOSQ_ERR_SUCCESS;
}
int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) {
// 清理资源
return MOSQ_ERR_SUCCESS;
}
int mosquitto_auth_security_init(void *user_data, struct mosquitto_opt *opts, int opt_count, bool reload) {
// 安全初始化
return MOSQ_ERR_SUCCESS;
}
int mosquitto_auth_acl_check(void *user_data, int access, const struct mosquitto *client, const struct mosquitto_msg *msg) {
// ACL检查
// return MOSQ_ERR_SUCCESS or MOSQ_ERR_ACL_DENIED
}
12.4 常用插件
Redis认证插件
bash
# 安装
git clone https://github.com/aclindsa/mosquitto-auth-plugin.git
cd mosquitto-auth-plugin
make
sudo make install
# 配置
auth_plugin /usr/lib/mosquitto/auth-plugin.so
auth_opt_backends redis
auth_opt_redis_host localhost
auth_opt_redis_port 6379
auth_opt_redis_db 0
HTTP认证插件
bash
# 配置HTTP API认证
auth_opt_backends http
auth_opt_http_getuser_uri http://api.example.com/auth/user
auth_opt_http_aclcheck_uri http://api.example.com/auth/acl
HTTP API实现示例
python
# Flask API示例
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/auth/user', methods=['POST'])
def auth_user():
data = request.json
username = data.get('username')
password = data.get('password')
# 验证逻辑
if verify_user(username, password):
return jsonify({'result': 'allow'})
return jsonify({'result': 'deny'}), 403
@app.route('/auth/acl', methods=['POST'])
def auth_acl():
data = request.json
username = data.get('username')
topic = data.get('topic')
acc = data.get('acc') # 1=read, 2=write
# ACL检查逻辑
if check_acl(username, topic, acc):
return jsonify({'result': 'allow'})
return jsonify({'result': 'deny'}), 403
12.5 消息拦截插件
消息到达
插件拦截
检查/修改
记录日志
增强数据
继续处理
12.6 本章小结
了解了Mosquitto的插件机制和扩展开发。