1

I appreciate any help.

I'm trying to connect to a SharePoint Online site from my ASP.NET Web Application built with .NET Framework 4.7.2

I have created a Self-Signed Certificate which is already installed on my development machine and is uploaded to an Azure App Registrations (client app), also created by myself:

Certificate installation on dev machine

enter image description here

Certificate uploaded to App Registration

enter image description here

The Azure App Registration (client app) is configured with a couple of API Permissions, one of them addressed to interact with the SharePoint data:

API Permissions - SharePoint Full Control

enter image description here

When a Http Request is done, the line of code that should get access token not responds but it does not throw error neither:

Line of code to generate access token

enter image description here

I have created several certificates, putting DnsName equals to localhost, but it does not work.

Conclusion: I need to get an access token every time a http request is done from a front-end application so my app be able to manage the information on SharePoint side.

Stuck code at line where access token sholud be generated

  • Use `.Result` at the end of the `AcquireTokenForClient`. `authResult = await azureApp.AcquireTokenForClient(scopes).ExecureAsync().Result`. – Harshitha Mar 15 '23 at 10:34
  • Hi Harshitha. Thanks in advance for your response. That line of code was already put on my code, the issue is when debugging the code it stucks and does not pass: – Cesar Torres Torres Mar 16 '23 at 14:45
  • Hello Cesar Literally, I’m facing the same issue with connecting SharePoint with .NET Framework Web Application. Debugging stuck in the same place as you highlighted and never come back. Did you find any reasonable solution for this issue? I’m using : - .NET Framework 4.8.1 - MVC 5.2 - Microsoft.SharePointOnline.CSOM 16.1.23xx – PeterS Apr 26 '23 at 12:53
  • Hi @PeterS Please to review my recent post by answering this question by myself – Cesar Torres Torres Apr 27 '23 at 14:46
  • Hi @CesarTorresTorres, could you tell me which version of Microsoft.SharePointOnline.CSOM and Microsoft.Identity.Client did you used ? – PeterS May 04 '23 at 07:51
  • Hi @PeterS, I apologise cause I was out for some days. I am using: - Microsoft.SharePointOnline.CSOM 16.1.21411.12000 - Microsoft.Identity.Client 4.30.1 – Cesar Torres Torres May 08 '23 at 21:12

1 Answers1

1

Hi all and thanks in advance for support provided.

I found a way to fix my issue.

Basically I have converted all methods that call the AccessToken method to async ones, it means, from Web method (controller) to internal ones they are all async now. Below are all the methods that call each other until to invoke the AccessToken method:

public class SharePointController : ApiController
{
    [AllowAnonymous]
    [HttpGet]
    [Route("api/sharepoint/connect")]
    public async Task<bool> Connect()
    {
        var obj = new SPConnection())
        
        return await obj.ConnectWithToken();
        
    }
}
    
    
    public class SPConnection
        {
    public async Task<bool> ConnectWithToken()
        {
            var authority = $"https://login.microsoftonline.com/{this.AzureTenantId}/";
            var token = await GetAccessToken(this.AzureCertFile, this.AzureCertPassword, this.AzureClientId, this.AzureTenantId, this.AzureTenantName, authority);
    
            using (var context = new ClientContext(this.SiteUrl))
            {
                context.ExecutingWebRequest += (s, e) =>
                {
                    e.WebRequestExecutor.RequestHeaders["Authorization"] =
                        "Bearer " + token;
                };
    
                this.Web = context.Web;
                context.Load(Web,
                               w => w.Title,
                               w => w.Url,
                               w => w.Lists);
                await context.ExecuteQueryAsync();
    
                this.ClientCtx = context;
            }
    
            return true;
        }
    
        private async Task<string> GetAccessToken(string azureCertFile, string azureCertPassword, string azureClientId, string azureTenantId, string azureTenantName, string authority)
        {
            /*REQUIRED CODE HERE TO DO THIS WORKS*/
    
            try
            {
                authResult = await azureApp.AcquireTokenForClient(spScopes).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                // The application doesn't have sufficient permissions.
                // - Did you declare enough app permissions during app creation?
                // - Did the tenant admin grant permissions to the application?
            }
            catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
            {
                // Invalid scope. The scope has to be in the form "https://resourceurl/.default"
                // Mitigation: Change the scope to be as expected.
            }
            catch (Exception ex)
            {
                //Other type of exceptions
            }
    
            return authResult != null ? authResult.AccessToken : null;
        }
        }