I'm currently building a .NET Core App which performs direct SharePoint REST calls to: contoso.sharepoint.com/sites/shipment/_api/search/query?querytext='...'
The .NET Core App is registerd in the Application Registrations. How do I retrieve the Access Token? (For some reason MS Graph API is not able to make these calls, hence trying SPO REST API)
CodePudding user response:
You could use the certificate way to get the token like this:
private static async Task<string> GetToken()
{
string applicationId = "xxx";
string tenantId = "contoso.onmicrosoft.com";
X509Certificate2 certificate = new X509Certificate2(@"C:\certificate.pfx", "password");
IConfidentialClientApplication confApp = ConfidentialClientApplicationBuilder.Create(applicationId)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.WithCertificate(certificate) // This is just a local method that gets the certificate on my machine
.Build();
var scopes = new[] { "https://contoso.sharepoint.com/.default" };
var authenticationResult = await confApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authenticationResult.AccessToken;
}
CodePudding user response:
I'm using the following code for public client application
public async Task<string> GetTokenAsync()
{
var clientId = "{client_id}";
var tenantId = "{tenant_id}";
var instance = "https://login.microsoftonline.com";
IPublicClientApplication clientApp = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority($"{instance}/{tenantId}")
.WithDefaultRedirectUri()
.Build();
var accounts = await clientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
var scopes = new[] { "https://contoso.sharepoint.com/.default" };
var userName = "{user}";
SecureString password = ...;
AuthenticationResult authResult;
try
{
authResult = await clientApp.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
authResult = await clientApp
.AcquireTokenByUsernamePassword(scopes, userName, password)
.ExecuteAsync();
}
return authResult.AccessToken;
}