如何使用 Web 应用程序/WebAPI 验证 Azure AD 中的用户凭据

Kri*_*rma 0 c# credentials azure asp.net-web-api azure-active-directory

我有一个网络应用程序。在主页中,用户将输入凭据,系统应根据 Azure AD 进行验证并继续进行。

当我使用本机应用程序并使用 时UserCredentials,它会验证用户,但如果我对 WebAPI 使用相同的方法,则会引发异常

请求正文必须包含以下参数:“client_secret 或 client_assertion”

当我使用 WebAPI using 时clientCredentials,它会生成 accessToken,它不会验证用户凭据。我还尝试在随后的调用中将凭据作为 httpclient 标头的一部分传递,尽管凭据错误,但它仍然有效。

string AzureADSTSURL = "https://login.windows.net/{0}/oauth2/token?api-version=1.0";
string GraphPrincipalId = "https://graph.windows.net";

string userid = "userid";
string password = "pass";

string tenantId = "axxx";   //  webapi
string clientId = "bxxx";
string clientSecret = "cxxx";
string authString = String.Format(AzureADSTSURL, tenantId);

var context = new AuthenticationContext(authString);

UserCredential userCredentials = new UserCredential(userid, password);
AuthenticationResult authenticationResult = context.AcquireToken(GraphPrincipalId.ToString(), clientId, userCredentials); // this works only if the clientId corresponds to a native app

ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = context.AcquireToken(GraphPrincipalId, clientCredential);


HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(result.AccessToken, Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userid + ':' + password)));

httpClient.GetAsync("http://localhost:11455/Login.aspx");
Run Code Online (Sandbox Code Playgroud)

有没有办法在不使用本机应用程序的情况下验证凭据?我认为 Graph API 不是正确的选择。

小智 5

我试图做同样的事情,但遇到了同样的错误:

请求正文必须包含以下参数:“client_secret 或 client_assertion”

我在上面敲了一会儿,然后在 twitter 上点击了 AzureSupport。

事实证明,只有将 Azure AD 应用程序设置为Native Client Application. 如果将其设置为 a,Web Application则会出现该错误,因为在 Azure AD 中访问 Web 应用程序的唯一方法是通过客户端 ID + 机密。

您可以在单个 AD 之上拥有多个应用程序,因此您只需将第二个应用程序设置为本机客户端即可验证该目录中的相同用户。