I have console application and want to create MSAL token.
I tried below code #
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId).WithAuthority(authority).Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result = null;
if (accounts.Any())
{
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
else
{
try
{
result = await app.AcquireTokenByUsernamePassword(scopes, "[email protected]", "joepassword").ExecuteAsync();
}
catch (MsalException)
{
// Handle various potential exceptions.
}
}
not able get AllowAnonymus token any idea?
1
There are several MSAL samples here, both in the context of a user (desktop) and an application (daemon).
1
Note that: If you want to generate the user access token without redirection, then the only way is
AcquireTokenByUsernamePassword
but this flow is not recommended by Microsoft due to security reasons.
Hence if you want user access token, then redirect is mandatory and If your setup supports redirection then you can make use of user interactive flows. Check this MsDoc as suggested by @rbrayb.
Otherwise, you can make use of Client credential flow which uses the application that accesses the API with its own identity and with no user interaction.
- This requires application type API permission to be granted to the application.
class Program
{
static async Task Main(string[] args)
{
string tenantId = "TenantID";
string clientId = "ClientID";
string clientSecret = "Secret";
string scope = "https://graph.microsoft.com/.default";
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(new[] { scope });
AccessToken token = await clientSecretCredential.GetTokenAsync(tokenRequestContext);
Console.WriteLine($"Token: {token.Token}");
Console.WriteLine($"Expires On: {token.ExpiresOn}");
}
}
If the application context doesn’t suit your scenario, then by default you need to generate token with redirect like below:
class Program
{
private static async Task Main(string[] args)
{
var scopes = new[] { "User.Read" };
var tenantId = "TenantID";
var clientId = "ClientID";
var options = new InteractiveBrowserCredentialOptions
{
TenantId = tenantId,
ClientId = clientId,
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
RedirectUri = new Uri("http://localhost"),
};
var interactiveCredential = new InteractiveBrowserCredential(options);
TokenRequestContext tokenRequestContext = new TokenRequestContext(scopes);
AccessToken accessToken;
try
{
accessToken = await interactiveCredential.GetTokenAsync(tokenRequestContext);
Console.WriteLine($"Access Token: {accessToken.Token}");
}
catch (Exception ex)
{
Console.WriteLine($"Error getting access token: {ex.Message}");
return;
}
}
}
User is redirected to sign-in:
Reference:
Choose an authentication provider | Microsoft