[sharepoint]文档库,文件夹授权

写在前面

在项目中用到了文档库授权的方法,这里将查询到的方式总结一下。

涉及到的方法

在逻辑中用到的方法。

[sharepoint]文档库,文件夹授权
    /// <summary>
        /// 获取sharepoint站点角色定义 rest api
        /// </summary>
        /// <param name="hostWebUrl"></param>
        /// <param name="strAPI"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private static ArrayList GetRoleDefinition(string hostWebUrl, string strAPI, string userName, string pwd, string domain)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader sr = null;
            strAPI = hostWebUrl + strAPI;
            ArrayList lstRoleDefinition = new ArrayList();
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(strAPI);
                request.Credentials = new NetworkCredential(userName, pwd, domain);
                request.Method = "GET";
                request.Accept = "application/json;odata=verbose";
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        JObject jobj = JObject.Parse(sr.ReadToEnd());
                        var results = jobj["d"]["results"];
                        foreach (var item in results)
                        {
                            lstRoleDefinition.Add(new
                            {
                                Id = Convert.ToInt32(item["Id"]),
                                Description = item["Description"] != null ? item["Description"].ToString() : "",
                                Hidden = Convert.ToBoolean(item["Hidden"]),
                                Name = item["Name"] != null ? item["Name"].ToString() : "",
                                Order = Convert.ToInt32(item["Order"]),
                                RoleTypeKind = Convert.ToInt32(item["RoleTypeKind"]),
                                BasePermissions = new
                                {
                                    High = item["BasePermissions"]["High"] != null ? item["BasePermissions"]["High"].ToString() : "",
                                    Low = item["BasePermissions"]["Low"] != null ? item["BasePermissions"]["Low"].ToString() : ""
                                }
                            });
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return lstRoleDefinition;
        }
        /// <summary>
        /// 将用户添加到sharepoint站点。
        /// </summary>
        /// <param name="hostWebUrl"></param>
        /// <param name="addUserName"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private static object AddUserToSharePointSite(string hostWebUrl, string addUserName, string userName, string pwd, string domain)
        {
            if (hostWebUrl.Contains("https"))
            {
                //如果请求的站点是https的url,则使证书的认证返回true。
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =>
                {
                    return true;
                });
            }
            try
            {
                ClientContext spContext = new ClientContext(hostWebUrl);
                spContext.Credentials = new NetworkCredential(userName, pwd, domain);
                Web web = spContext.Web;
                string loginName = @"i:0#.w|" + domain + "" + addUserName;
                User user = web.EnsureUser(loginName);
                //需要load,不然拿不到user的属性
                spContext.Load(user);
                spContext.ExecuteQuery();
                return new { Email = user.Email, Id = user.Id, LoginName = user.LoginName, Title = user.Title };
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }
        public static string GetContextinfo(string hostWebUrl, string userName, string pwd, string domain)
        {
            HttpWebRequest contextInfoRequest = null;
            HttpWebResponse endpointResponse = null;
            StreamReader sr = null;
            string strJson = string.Empty;
            try
            {
                //获取contextinfo
                contextInfoRequest = (HttpWebRequest)HttpWebRequest.Create(hostWebUrl + "/_api/contextinfo");
                contextInfoRequest.Method = "POST";
                contextInfoRequest.Credentials = new NetworkCredential(userName, pwd, domain);
                contextInfoRequest.Accept = "application/json;odata=verbose";
                contextInfoRequest.ContentLength = 0;
                using (endpointResponse = (HttpWebResponse)contextInfoRequest.GetResponse())
                {
                    using (sr = new StreamReader(endpointResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                        JObject jobj = JObject.Parse(strJson);
                        return jobj["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 将用户添加到sharepoint站点。rest api方式
        /// </summary>
        /// <param name="hostWebUrl"></param>
        /// <param name="addUserName"></param>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private static string AddUserToSharePointSite(string hostWebUrl, bool isRestAPI, string addUserName, string userName, string pwd, string domain)
        {
            string data = "{ '__metadata': { 'type': 'SP.User' }, 'LoginName':'i:0#.w|membership|" + addUserName + "'}";
            string strAPI = "_api/Web/siteusers";
            HttpWebRequest request = null;
            StreamReader sr = null;
            HttpWebResponse response = null;

            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(hostWebUrl + "/" + strAPI);
                request.Method = "POST";
                if (!string.IsNullOrEmpty(data))
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(data);
                    request.ContentLength = buffer.Length;
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        requestStream.Write(buffer, 0, buffer.Length);
                    }
                }
                else
                {
                    request.ContentLength = 0;
                }
                request.Credentials = new NetworkCredential(userName, pwd, domain);
                request.Accept = "application/json;odata=verbose";
                request.ContentType = "application/json;odata=verbose";
                request.Headers.Add("X-RequestDigest", GetContextinfo(hostWebUrl, userName, pwd, domain));
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 为文件夹授权
        /// </summary>
        /// <param name="currentCoworkLibrary"></param>
        /// <param name="strCheckUser"></param>
        private static void AssignToUserReadPermissionToFolder(string hostWebUrl, string folderServerRelativeUrl, string strCheckUser, string userName, string pwd, string domain)
        {
            //https,取消https证书认证
            if (hostWebUrl.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) =>
                {
                    return true;
                });
            }
            try
            {
                ServicePointManager.Expect100Continue = false;
                ClientContext spContext = new ClientContext(hostWebUrl);

                spContext.Credentials = new NetworkCredential(userName, pwd, domain);
                Web web = spContext.Web;
                string loginName = @"i:0#.w|" + domain + "\\" + strCheckUser;

                Principal user = web.EnsureUser(loginName);
                spContext.ExecuteQuery();
                Folder folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
                var roleDefinition = spContext.Site.RootWeb.RoleDefinitions.GetByType(RoleType.Reader);
                var roleBindings = new RoleDefinitionBindingCollection(spContext) { roleDefinition };
                spContext.ExecuteQuery();
                if (folder != null)
                {
                    folder.ListItemAllFields.BreakRoleInheritance(true, false);
                    folder.ListItemAllFields.RoleAssignments.Add(user, roleBindings);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
[sharepoint]文档库,文件夹授权

另外加个rest api,这种方式也可以进行授权。

_api/web/lists/getByTitle('" + LibraryName + "')/RoleAssignments/addroleassignment(principalid=" + userId + ",roledefid=" + roleDefinitionId + ")"

 总结

 在对文档库或者文件夹进行授权的过程,总是磕磕碰碰,不管怎么,最后还是实现了。总结在这里,方便以后查询

博客地址: http://www.cnblogs.com/wolf-sun/
博客版权: 本文以学习、研究和分享为主,欢迎转载,但必须在文章页面明显位置给出原文连接。
如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步!
再次感谢您耐心的读完本篇文章。http://www.cnblogs.com/wolf-sun/p/4980034.html

上一篇:jquery升级到新版本报错[jQuery] Cannot read property ‘msie’ of undefined错误的解决方法


下一篇:hr换行符的颜色设置