How to do Get-MsalToken in C#

241 views Asked by At

I can get a bearer token using these parameters Get-MsalToken -ClientId '' -TenantId '' -Scopes ''

I am trying to convert it to use C# instead of PowerShell:

var clientId = "xyz";
var tenantId = "xyz";

// We intend to obtain a token for Graph for the following scopes (permissions)
string[] scopes = { $"{clientId}/.default" };

string authority = $"https://login.microsoftonline.com/{tenantId}";

IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId)
    .WithAuthority(new Uri(authority))
    .WithRedirectUri("http://localhost")
    .Build();

AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
var token =  result.AccessToken;

But I get an error saying: "The redirect URI 'http://localhost' specified in the request does not match the redirect URIs configured for the application"

1

There are 1 answers

4
Orifjon On

This is happening because your app in Azure is not configured to redirect to localhost. You need to update it in Azure portal. See: https://learn.microsoft.com/en-us/troubleshoot/azure/active-directory/error-code-aadsts50011-redirect-uri-mismatch