我是 Azure AD 新手,并尝试使用受 AD 保护的 api。我已经成功创建并保护了 api,但在我的 Windows 窗体应用程序中很难使用它。我已尝试过Link处的文档,但在这一行中出现编译时错误
AuthenticationResult ar =
ac.AcquireToken("https://cloudidentity.net/WindowsAzureADWebAPITest",
"a4836f83-0f69-48ed-aa2b-88d0aed69652",
new Uri("https://cloudidentity.net/myWebAPItestclient"));
现在 ADAL 中没有这样的方法。我尝试过一个异步版本,但采用不同的参数
AuthenticationResult ar =
ac.AcquireTokenAsync("https://cloudidentity.net/WindowsAzureADWebAPITest",
"a4836f83-0f69-48ed-aa2b-88d0aed69652",
new Uri("https://cloudidentity.net/myWebAPItestclient"), IPlatformParameters);
除了其他信息之外,它还需要 IPlatformParameters 对象,但我对此一无所知。我尝试传递 null 并继续,但此行出现错误
string authHeader = ar.CreateAuthorizationHeader();
错误是 ar 对象的 ADAL 中没有这样的方法。所以我跳到这个 tutorial因为他也在使用 Windows Forms 应用程序。他写的代码是
Task<AuthenticationResult> ar = authContext.AcquireTokenAsync("https://carsforher.onmicrosoft.com/SecuredCars_20160722021100", "2640aca3-a35e-42f8-8f6d-2e5fe1a09df4", new Uri("http://localhost"), null);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ar.AccessToken).....
但是 ar 对象没有 AccessToken 属性。然后我尝试从 Azure Documentation 下载示例应用程序,但他们也编写了完全相同的代码,不幸的是这不起作用。我使用的 ADAL 版本是 3.12.0.827。请帮助我弄清楚如何获取访问 token 并使用 api。
最佳答案
您错误地使用了 AcquireTokenAsync:AcquireTokenAsync 返回一个任务,而不是 AuthenticationResult 对象,因此方法“CreateAuthorizationHeader”和属性“AccessToken”(并非真正)“丢失”。
代码的固定版本将是:
AuthenticationResult ar = ac.AcquireTokenAsync("https://cloudidentity.net/WindowsAzureADWebAPITest",
"a4836f83-0f69-48ed-aa2b-88d0aed69652",
new Uri("https://cloudidentity.net/myWebAPItestclient"), IPlatformParameters).Result;
string authHeader = ar.CreateAuthorizationHeader();
string accessToken = ar.AccessToken;
或或者,这样你的代码将真正异步运行,你可以将“async”添加到方法签名中并执行以下操作:
AuthenticationResult ar = await ac.AcquireTokenAsync("https://cloudidentity.net/WindowsAzureADWebAPITest",
"a4836f83-0f69-48ed-aa2b-88d0aed69652",
new Uri("https://cloudidentity.net/myWebAPItestclient"), IPlatformParameters);
string authHeader = ar.CreateAuthorizationHeader();
string accessToken = ar.AccessToken;
关于c# - Azure AD 从身份验证结果对象获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38526362/