I am trying to customize some lists for SharePoint Online and since I am new to the subject I do not know how to connect to the service.

When I use NAPA and from the cloud use the option "Edit in Visual Studio", I am prompted for credentials automatically when the project opens. However, when I start from bottom-up, i.e. open a new project in Visual Studio, add all necessary dlls, this part of code throws an error (it is an authentication issue):

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

I am using Microsoft.SharePoint.Client;

The error message:

An unhandled exception of type 'System.Net.WebException' occurred in Microsoft.SharePoint.Client.dll Additional information: The remote server returned an error: (403) Forbidden.

I think I am missing part of the code which is responsible for authentication and which in case of NAPA app is hard-coded.

How can I authenticate to SharePoint Online? (it is enough if my code runs just once, it's not an app, I don't want to package it and publish)

I am guessing it has something to do with http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.sharepoint.remote.authentication.aspx, but that's as far as I got.

有帮助吗?

解决方案

How to authenticate against SharePoint Online using the managed CSOM

The CSOM for SharePoint 2013 introduces the SharePointOnlineCredentials class that allows to perform an active authentication to SharePoint Online.

Example

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;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top