Kirk Evans Blog

.NET From a Markup Perspective

Call O365 using CSOM with a Console Application

Call O365 using CSOM with a Console Application

Rate This
  • Comments 10

This post shows how to use the SharePointOnlineCredentials class to authenticate to O365 from a console application.

Background

I write a ton of short samples for customers and co-workers.  I’ve written this one quite a few times but never seemed to add it to my personal source code control repository in the cloud (you are aware that you can get TFS in the cloud for free with Visual Studio Online, right?)  As I started adding this code to TFS today, I realized that I should also blog this one as it may help someone else.

In 2011, Wictor Wilen wrote a fantastic post that showed how to do active authentication to Office 365 and SharePoint Online.  While that post is still very accurate, that functionality has been brought into the client side object model so that you do not have to write this code yourself.  The CSOM for SharePoint 2013 introduces the new SharePointOnlineCredentials class that provides this functionality.

Show Me the Code!

To show you how easy this is, here is a Console application that uses the SharePointOnlineCredentials class to get a remote site’s Title property.

using System;
using System.Security;
using Microsoft.SharePoint.Client;

namespace MSDN.Samples
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleColor defaultForeground = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter the URL of the SharePoint Online site:");

            Console.ForegroundColor = defaultForeground;
            string webUrl = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your user name (ex: kirke@mytenant.microsoftonline.com):");
            Console.ForegroundColor = defaultForeground;
            string userName = Console.ReadLine();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Enter your password.");
            Console.ForegroundColor = defaultForeground;
            SecureString password = GetPasswordFromConsoleInput();

            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new SharePointOnlineCredentials(userName,password);
                context.Load(context.Web, w => w.Title);
                context.ExecuteQuery();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Your site title is: " + context.Web.Title);
                Console.ForegroundColor = defaultForeground;
            }
        }

        private static SecureString GetPasswordFromConsoleInput()
        {
            ConsoleKeyInfo info;

            //Get the user's password as a SecureString
            SecureString securePassword = new SecureString();
            do
            {
                info = Console.ReadKey(true);
                if (info.Key != ConsoleKey.Enter)
                {
                    securePassword.AppendChar(info.KeyChar);
                }
            }
            while (info.Key != ConsoleKey.Enter);
            return securePassword;
        }
    }
}

Once you run the application, supply the URL, username, and password of a user that has permission to access the site using CSOM.  Here is what the output looks like:

image

For More Information

how to do active authentication to Office 365 and SharePoint Online

SharePointOnlineCredentials class

Connecting to Office 365 using Client Side Object Model and Web Services

Using PowerShell and the .NET CSOM to Query SharePoint 2013 Online

  • Hi, nice stuff, but what about Single Sign-On, for example if company has AD FS for Office 365 and wants to authenticate. I believe this is not supported by SharePointOnlineCredentials class.

  • @Hrvoje - I used this same exact code to log into my corporate O365 site without issues, and we use ADFS to provide SSO internally at Microsoft.

  • I'm getting an IDCRLException: "Identity Client Runtime Library (IDCRL) could not look up the realm information for a federated sign-in." just trying to create an instance of SharePointOnlineCredentials with the username and password we have set-up for our SharePoint Online site - any clues?

  • I am getting the same error as wizofaus above when connecting with an Odata connection is SSIS using the newly updated Odata source for SQL 2012 (www.microsoft.com/.../details.aspx). Can you help?

  • SharePointOnlineCredentials is only intended to be used from a Windows Forms or a Console app.  If you are trying in other contexts, you should use OAuth instead.

    I've seen IDCRL errors previously when some of the required assemblies were missing.  Create a new Console application.  Right-click the project and choose Manage NuGet Packages.  Search for "sharepoint app" and install the "App for SharePoint Web Toolkit" package.  Run the application.  Worked fine for me against 3 different O365 tenants.  

    If you are packaging the Console app to use somewhere else, some things to try:

    1. If your EXE is 64 bit, copy MSOIDCLIL.DLL and MSOIDRES.DLL from \Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\Client directory to the same directory as your EXE.

    2. If your EXE is 32 bit, copy MSOIDCLIL.DLL and MSOIDRES.DLL from \Program Files (x86)\Common Files\Microsoft Shared\Web Server Extensions\15\Client directory to the same directory as your EXE.

  • SharePointOnlineCredentials does not work with federated logins. It's all over blogs and articles on the internet...

    Simple way to test is to get a SharePoint online site, add an external user, and try to auth with a console app using SharePointOnlineCredentials().

    Every time you will get an idcrl exception with that user. Any onmicrosoft.com user will work just fine on the same site.

    Kirk, I don't know what's different about your environment, but this is 10 lines of code. I don't think it's a programming mistake.

    It would be very nice to understand what's different so we can get this fixed.

    An unhandled exception of type 'Microsoft.SharePoint.Client.IdcrlException' occurred in Microsoft.SharePoint.Client.Runtime.dll

  • Hi

    Is there any code snippet with CSOM to access Online Search Service Application from on premise in SharePoint 2013 ??

  • I am trying to connect to a O365 tenant using this method, but i am getting this error message:

    "An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

    Additional information: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method."

    When connecting to another tenant using the same code, it works without problem. If i run the code from an old 2008 server, connection to both tenants works fine. Have tested the tenant that fails on many different client configurations, but only my 2008 server works. Any tips or ideas ?

  • Hi Lars Erik ,

    I had faced the same issue.

    But for me it was firewall issue.

    I would suggest to check ur firewall before u run the code.

    Regards,

    Avinash

  • Hi,

    I am getting an error "The remote server returned an error: (401) Unauthorized." the un and password I am using are correct and I am able to login using the browser.

    stacktrace:

      at System.Net.HttpWebRequest.GetResponse()

      at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.GetCookie(Uri url, String endpoint, String ticket, Boolean throwIfFail, EventHandler`1 executingWebRequest)

      at Microsoft.SharePoint.Client.Idcrl.SharePointOnlineAuthenticationProvider.GetAuthenticationCookie(Uri url, String username, SecureString password, Boolean alwaysThrowOnFailure, EventHandler`1 executingWebRequest)

      at Microsoft.SharePoint.Client.SharePointOnlineCredentials.GetAuthenticationCookie(Uri url, Boolean refresh, Boolean alwaysThrowOnFailure)

      at Microsoft.SharePoint.Client.ClientRuntimeContext.SetupRequestCredential(ClientRuntimeContext context, HttpWebRequest request)

      at Microsoft.SharePoint.Client.SPWebRequestExecutor.GetRequestStream()

      at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()

      at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()

      at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()

      at SharepointAccessList.Program.Main(String[] args) in C:\Users\batchur\documents\visual studio 2010\Projects\ConsoleApplication2\ConsoleApplication2\Class1.cs:line 25

      at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

      at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

      at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

      at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

      at System.Threading.ThreadHelper.ThreadStart()

Page 1 of 1 (10 items)
Leave a Comment
  • Please add 3 and 6 and type the answer here:
  • Post
Translate This Page
Search
Archive
Archives