How to allow access for my self-created .NET application to Sharepoint Online using CSOM

lieee01 1 Reputation point
2021-06-10T06:25:51.147+00:00

I was working on a project that create a .NET desktop application that able to connect Sharepoint Online and retrieve list of item from Sharepoint Online. But I was struggling due to authentification issue. My company was using Microsoft 365 to access Sharepoint Online.

I was trying to make my app to use window credentials to acess SP but it doesn't work.

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

This error will come out when I do ExecuteQuery().

I know there is a way by passing the username and password through SharePointOnlineCredentials method, but I don't have password to pass through. How to allow using DefaultCredentials to access SP?

Languages: VB.net

Anyone can advice me on how to solve this issue?

I need helps urgently!

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,726 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MichaelHan-MSFT 18,016 Reputation points
    2021-06-11T02:50:22.293+00:00

    Hi @lieee01 ,

    The windows credentials(DefaultCredentials) is not supported to access SharePoint Online site.

    You need to use SharePointOnlineCredentials for authentication, the username and password is the Microsoft 365 accounts of your organization to access SharePoint Online. Below is a sample to access SharePoint Online:

            String name = "userName@tenant.onmicrosoft.com";  
            String password = "xxxx";  
            SecureString securePassword = new SecureString();  
            foreach (char c in password.ToCharArray())  
            {  
                securePassword.AppendChar(c);  
            }  
            var credentials = new SharePointOnlineCredentials(name, securePassword);  
            var siteUrl = "https://yourSite.sharepoint.com/sites/test";  
            ClientContext ctx = new ClientContext(siteUrl);  
    		Web web = ctx.Web;  
            ctx.Load(web);  
            ctx.ExecuteQuery();  
    

    Besides, you could use app only with client Id and client secret to access SharePoint Online, this requires you register an app and grant permissions for the app. You could refer to this official article for more: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.