skip to Main Content

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"

2

Answers


  1. 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

    Login or Signup to reply.
  2. I have reproduced in my environment and below are my expected results:

    Code which worked for me:

    using Microsoft.Identity.Client;
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var temptok  = ConfidentialClientApplicationBuilder
                .Create("clientid")
                .WithClientSecret("clientsecret")
                .WithAuthority(new Uri("https://login.microsoftonline.com/tenantid"))
                .Build();
            string[] rithscopes = new string[] { "clientid/.default" };
    
            var solution = await temptok.AcquireTokenForClient(rithscopes)
                .ExecuteAsync();
    
            Console.WriteLine($"Hello Rithwik the token is  :n{solution.AccessToken}");
        }
    }
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search