专业IM即时通讯软件开发,值得信赖!

OpenFire通过User Service管理用户

openfire 云聊IM 51℃

安装User Service插件

在管理控制平台找到选项卡“插件”,里边有我们需要安装的一个User Service插件,如果安装过了会显示已经安装的哪些插件,没有安装,需要点击左侧菜单“有效的插件”,在列表里找到此插件进行安装,可能有点慢,稍等即可。如果在有效的插件列表没有发现很多的插件,那么你需要重新安装openfire服务器或者升级最新版本。

设置User Service插件

在选项卡“服务器”找到“服务器设置”下有个菜单“User Service”,说明安装插件成功,但是还是需要进行设置才能通过端口进行访问,不然无法访问或者报错401未授权等。设置:Enabled – User service requests will be processed. 启用、勾选HTTP basic auth – User service REST authentication with Openfire admin account. 如果选择Secret key auth,那C#写着太麻烦,通过访问接口需要传Secret key的值,否则就是报错401。

还可以在系统属性里添加进行设置接口是否启用,需要设置2项值如下图:

代码示例

/// <summary>
/// 获取所有openfire用户
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
       //这个地方的地址和用户名密码我是从配置文件读取的,大家可以直接赋值。
	string url = CachedConfigContext.Current.SettingConfig.OpenFireServer + "plugins/userService/users";
	WebRequest req = WebRequest.Create(url);
	req.Method = "GET";
	string username = CachedConfigContext.Current.SettingConfig.OpenFireUsername;
	string password = CachedConfigContext.Current.SettingConfig.OpenFirePassword;
	string usernamePassword = username + ":" + password;
	CredentialCache mycache = new CredentialCache();
	mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
	req.Credentials = mycache;
	req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
	WebResponse result = null;
	try
	{
		result = req.GetResponse();
		Stream ReceiveStream = result.GetResponseStream();
		//read the stream into a string
		StreamReader sr = new StreamReader(ReceiveStream);
		string resultstring = sr.ReadToEnd();
		if (!string.IsNullOrEmpty(resultstring))
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(resultstring);
			var xmlModel = XmlToObjList<OpenFireUser>(resultstring, "user");
			this.ViewBag.existUsers = string.Join(",", xmlModel.Select(s => s.username));
			return View(xmlModel);
		}

	}
	catch (Exception exp)
	{

	}
	finally
	{
		if (result != null)
		{
			result.Close();
		}
	}
	return View();
}

/// <summary>  
/// xml文件转化为实体类列表  
/// </summary>  
/// <typeparam name="T">实体名称</typeparam>  
/// <param name="xml">您的xml文件</param>  
/// <param name="headtag">xml头文件</param>  
/// <returns>实体列表</returns>  
public List<T> XmlToObjList<T>(string xml, string headtag)
	where T : new()
{

	List<T> list = new List<T>();
	XmlDocument doc = new XmlDocument();
	PropertyInfo[] propinfos = null;
	doc.LoadXml(xml);
	//XmlNodeList nodelist = doc.SelectNodes(headtag);  
	XmlNodeList nodelist = doc.GetElementsByTagName(headtag);
	foreach (XmlNode node in nodelist)
	{
		T entity = new T();
		//初始化propertyinfo  
		if (propinfos == null)
		{
			Type objtype = entity.GetType();
			propinfos = objtype.GetProperties();
		}
		//填充entity类的属性  
		foreach (PropertyInfo propinfo in propinfos)
		{
			//实体类字段首字母变成小写的  
			string name = propinfo.Name.Substring(0, 1) + propinfo.Name.Substring(1, propinfo.Name.Length - 1);
			XmlNode cnode = node.SelectSingleNode(name);
			if (cnode != null)
			{
				string v = cnode.InnerText;
				if (v != null)
					propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
			}
		}
		list.Add(entity);

	}
	return list;

}

最后会返回一个xml的文件,里边是所有用户的信息。

至于新增、删除的接口就不做案例里,你可以通过管理控制平台查找demo,里边有介绍如何访问接口,查看地址:http://192.168.3.66:9090/plugin-admin.jsp?plugin=userservice&showReadme=true&decorator=none

如下图点击图标就可以查看此插件的demo:

通过User Service添加用户:

[HttpPost]
public JsonResult syncUser(string existUsers)
{
	if (!string.IsNullOrEmpty(existUsers))
	{
		var array = existUsers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
		var Users = this.FoundationService.GetPersonMain(s => s.UnitID == this.CurrentManager.UnitID);
		foreach (var item in Users)
		{
			if (array.Contains(item.UserName.ToLower()))
			{
				continue;
			}

			var userXML = string.Format("<?xml version='1.0' encoding='UTF-8' standalone='yes'?> <user> <username>{0}</username> <password>{1}</password>  <name>{2}</name> <email>{3}</email></user>", item.UserName, item.Password, item.PersonName, item.Email);
			//通过openFire user service添加用户
			string url = CachedConfigContext.Current.SettingConfig.OpenFireServer + "plugins/userService/users";
			WebRequest req = WebRequest.Create(url);
			req.Method = "POST";
			string username = CachedConfigContext.Current.SettingConfig.OpenFireUsername;
			string password = CachedConfigContext.Current.SettingConfig.OpenFirePassword;
			string usernamePassword = username + ":" + password;
			CredentialCache mycache = new CredentialCache();
			mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
			req.Credentials = mycache;
			req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
			req.ContentType = "application/xml";

			byte[] byteArray = Encoding.UTF8.GetBytes(userXML);
			req.ContentLength = byteArray.Length;
			Stream dataStream = req.GetRequestStream();
			dataStream.Write(byteArray, 0, byteArray.Length);
			dataStream.Close();

			WebResponse result = null;
			try
			{
				result = req.GetResponse();
				Stream ReceiveStream = result.GetResponseStream();
				//read the stream into a string
				StreamReader sr = new StreamReader(ReceiveStream);
				string resultstring = sr.ReadToEnd();
			}
			catch (Exception exp)
			{
				return Json(new { success = false, msg = "同步失败!" + exp.Message });
			}
			finally
			{
				if (result != null)
				{
					result.Close();
				}
			}
		}
	}

	return Json(new { success = true, msg = "同步成功!" });
}
喜欢 (1)
仿微信聊天软件开发
点击这里给我发消息