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