Cesar Torres Torres
Cesar Torres Torres

Reputation: 21

How to get an access token to connect to SharePoint Online from an ASP.NET web application

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

Upvotes: 1

Views: 1577

Answers (1)

Cesar Torres Torres
Cesar Torres Torres

Reputation: 21

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;
        }
        }

Upvotes: 1

Related Questions