安裝OpenFire服務器略去
1.安裝User Service插件:
在管理控制平台找到選項卡“插件”,里邊有我們需要安裝的一個User Service插件,如果安裝過了會顯示已經安裝的哪些插件,沒有安裝,需要點擊左側菜單“有效的插件”,在列表里找到此插件進行安裝,可能有點慢,稍等即可。如果在有效的插件列表沒有發現很多的插件,那么你需要重新安裝openfire服務器或者升級最新版本。


2:
在選項卡“服務器”找到“服務器設置”下有個菜單“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項值如下圖:

3:然后就可以通過C#代碼進行訪問接口,獲取所有的用戶列表:
/// <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 = "同步成功!" }); }
