能否在控制台应用程序中使用AzureAD身份验证?

6
这个想法是让它像Azure Powershell一样工作,也就是说,标准的Active Directory身份验证对话框弹出,我输入我的凭据,AzureAD处理后,控制台应用程序就可以访问某个web服务。
这可能吗? 这不应该太难,但我找不到例子。
看着WPF示例,我发现它在app.config中设置了客户端id。这真的有必要吗?我的意思是,单页js应用程序也没有在AD中注册,对吧?

一个单页的JS应用程序需要在AD中注册才能使用AD身份验证。 - Justin
1
请访问以下链接以获取该项目的源代码:https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console - 4c74356b41
一个示例,其中控制台应用程序访问由Azure AD保护的Web API - https://blogs.msdn.microsoft.com/benjaminperkins/2016/10/20/how-i-connected-a-console-application-to-a-web-api-protected-by-an-azure-active-directory/ - alwayslearning
1个回答

5

实际上,任何客户端应用程序都应该在AAD中注册。

控制台应用程序也必须在Azure AD中注册,这样您就可以获得客户端ID和客户端重定向URL,但没有客户端密钥。然后以下代码应该可以正常工作:

void Main()
{
    var clientId = "client-GUID";
    var clientUrl = new Uri("redirect-url");  //can be anything starting with localhost
    var tenant = "name of your AAD tenant";
    string authority = "https://login.windows.net/" + tenant;

    string resource = "https://outlook.office365.com";  ///put id or url of resource you're accessing

    AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

    Console.WriteLine("Trying to acquire token");

    var pp = new PlatformParameters(PromptBehavior.Auto); //this brings web prompt
    var token = authenticationContext.AcquireTokenAsync(resource, clientId, clientUrl, pp, UserIdentifier.AnyUser).Result;
    Console.WriteLine("Got the token: {0}", token.AccessToken);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接