Authenticate network credential to access SharePoint site on client object model

Toxic picture Toxic · Jul 24, 2014 · Viewed 23.6k times · Source

I am working to small app, that is require to bring all users in all groups of given site. I have two sites; SharePoint 2010 running on premisses and SharePoint 2013 online. I am getting credential error...

{"The remote server returned an error: (401) Unauthorized."}

code.

 public class Program
{
    static void Main(string[] args)
    {

        string _siteURL = "https://intranet.co.uk";

        NetworkCredential _myCredentials = new NetworkCredential("user", "password", "https://intranet");

        ClientContext _clientContext = new ClientContext(_siteURL);

        _clientContext.Credentials = _myCredentials;

        Web _MyWebSite = _clientContext.Web;

        GroupCollection _GroupCollection = _MyWebSite.SiteGroups;

        _clientContext.Load(_GroupCollection);

        _clientContext.Load(_GroupCollection,
                             groups => groups.Include(group => group.Users)
             );

        _clientContext.ExecuteQuery();

        foreach (Group _group in _GroupCollection)
        {
            Console.WriteLine("Group Id   " + _group.Id + "     Group Title  " + _group.Title);

            UserCollection _userCollection = _group.Users;

            foreach (User _user in _userCollection)
            {
                Console.WriteLine("Group ID: {0} Group Title: {1} User: {2} Login Name: {3}", _user.Title, _user.LoginName);
            }

            Console.WriteLine("\n.......................................");
        }

        Console.Read();

    }

Answer

Marco picture Marco · Jul 24, 2014

Your credentials are wrong, espacially your domain.

NetworkCredential _myCredentials = new NetworkCredential("user", "password", "https://intranet");

Your useraccount is specified as domain\username and I doubt your domainname would be https://intranet, but rather companyname. If you are not sure, ask your Exchange administrator.

What you are looking for is something analog to this:

NetworkCredential _myCredentials = new NetworkCredential("user", "password", "companydomain");
//OR
NetworkCredential _myCredentials = new NetworkCredential(@"companydomain\user", "password");