[SharePoint] Use a non-password to log in with CSOM

1 minute read


Soon all .NET will be consolidated into .NET 5 (formerly Core), but it seems that SharePoint Online Credentials, which is standard for password authentication of CSOM, will not be available for this .NET 5.

Before that, people who are logged in with passwordless authentication will be in trouble, so the motivation is to deal with it.

.NET 5 or earlier

For .NET 5 or earlier, after inserting “SharePoint PnPCore Online” with NuGet,

var authenticationManager = new OfficeDevPnP.Core.AuthenticationManager();
ClientContext context = authenticationManager.GetWebLoginClientContext("<Site URL>", null);

It seems that you can do it with. (I haven’t tried it before .NET 5)

As of October 4, 2020, it did not work well in the .NET 5 environment.
I think it is related to the warning that it does not support .NET 5 at build time.

The method used this time

After using the PnP Core authentication library, retrieve the access token and initialize the CSOM ClientContext.

However, since PnP can handle not only SharePoint access similar to CSOM but also Microsoft Graph, there is no need to use CSOM unless you do not want to modify the resources implemented in CSOM as much as possible.


The sample is placed below.

  • You need to register the app in AAD in advance.

The point

After logging in using the helper of PnP.Core.Auth, retrieve the access token.

var accessToken =  await context.AuthenticationProvider.GetAccessTokenAsync(context.Uri);

After that, initialize it so that the token is added to the request header when creating the ClientContext of CSOM.

context.ExecutingWebRequest += (sender, e) =>
    // Insert the access token in the request
    e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;

You can still access SharePoint using ClientContext.

※important point

In the case of console apps, once you disconnect (Host.Dispose ()) and reconnect, the GetAccessTokenAsync method will deadlock and will not return.

Referenced site

Points to note with CSOM compatible with .NET Standard
Use CSOM for .NET Standard instead of CSOM in .NET Framework
PnP Core SDK
I want to configure my own Azure AD application