【问题标题】:How to authenticate against Sharepoint Online with user credentials?如何使用用户凭据对 Sharepoint Online 进行身份验证?
【发布时间】:2014-03-31 10:30:45
【问题描述】:

我正在尝试为 SharePoint Online 自定义一些列表,由于我是该主题的新手,我不知道如何连接到该服务。

当我使用 NAPA 并从云端使用“在 Visual Studio 中编辑”选项时,项目打开时会自动提示我输入凭据。 但是,当我从下往上开始,即在 Visual Studio 中打开一个新项目,添加所有必要的 dll 时,这部分代码会抛出错误(这是一个身份验证问题):

ClientContext context = new ClientContext("https://MYURL.sharepoint.com/n/"); 
context.ExecuteQuery();

我正在使用 Microsoft.SharePoint.Client;

错误信息:

Microsoft.SharePoint.Client.dll 中出现“System.Net.WebException”类型的未处理异常 附加信息:远程服务器返回错误:(403) Forbidden。

我认为我缺少负责身份验证的部分代码,并且在 NAPA 应用程序的情况下是硬编码的。

如何向 SharePoint Online 进行身份验证? (我的代码只运行一次就够了,不是app,我不想打包发布)

我猜它与http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.sharepoint.remote.authentication.aspx 有关系,但据我所知。

【问题讨论】:

    标签: visual-studio authentication sharepoint sharepoint-online


    【解决方案1】:

    如何使用托管 CSOM 对 SharePoint Online 进行身份验证

    SharePoint 2013 的 CSOM 引入了 SharePointOnlineCredentials class,它允许对 SharePoint Online 执行主动身份验证。

    示例

    class Program
    {
        static void Main(string[] args)
        {
    
            Console.WriteLine("Enter the URL of the SharePoint Online site:");
    
            string webUrl = Console.ReadLine();
    
            Console.WriteLine("Enter your user name (format: username@tenant.onmicrosoft.com)");
            string userName = Console.ReadLine();
    
            Console.WriteLine("Enter your password.");
            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.WriteLine("Your site title is: " + context.Web.Title);
            }
        }
    
        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;
        }
    }
    

    【讨论】:

    • 请注意,这将不再有效,因为 SharePoint(以及大多数 O365 应用程序/服务)需要新式身份验证。您将需要创建一个 Azure AD 应用并使用应用 ID 和密码才能进行连接,而不是使用用户凭据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多