In this article, we are going to learn, How to get the user permission on the site using csom or how to get the user permission programmatically, to get the permission of the user on a particular site we use GetUserEffectivePermissions() method in csom. In the SharePoint, user requires permission to perform any operation, when we work with provider-hosted add-ins and in some scenarios, we need to check the permission of user we use the GetUserEffectivePermissions() method and by passing the user name we get its effective permission on the site.
In this example, We have created a console application to check whether the user have edit person or not on site.
Pass the context of the site and email of the user into a method to check the permission of the user on the site. You must ensure users on the web before checking permission.
using System;
using System.Security;
using Microsoft.SharePoint.Client;
namespace PracticeCsom
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "https://***.sharepoint.com/sites/***/";
using (ClientContext clientContext = new ClientContext(siteUrl))
{
SecureString SecurePassword = GetSecureString("*****");
clientContext.Credentials = new SharePointOnlineCredentials("***@***.onmicrosoft.com", SecurePassword);
bool hasPermission = CheckPermissionOnDocumentlibrary(clientContext, "[email protected]");
if (hasPermission)
{
Console.WriteLine("User have permission");
}
else {
Console.WriteLine("User do not have permission on the site");
}
}
}
public static bool CheckPermissionOnDocumentlibrary(ClientContext clientContext, string userEmail)
{
bool haspermission = false;
try
{
if (clientContext != null)
{
Web web = clientContext.Web;
User user = web.EnsureUser(userEmail);
clientContext.Load(user);
clientContext.ExecuteQuery();
var permissions = web.GetUserEffectivePermissions(user.LoginName);
clientContext.ExecuteQuery();
if (permissions.Value.Has(PermissionKind.AddListItems))
{
haspermission = true;
}
}
return haspermission;
}
catch (Exception ex)
{
return haspermission;
}
}
private static SecureString GetSecureString(String Password)
{
SecureString oSecurePassword = new SecureString();
foreach (Char c in Password.ToCharArray())
{
oSecurePassword.AppendChar(c);
}
return oSecurePassword;
}
}
}
Comments
Post a Comment