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

标签 c# azure asp.net-web-api credentials azure-active-directory

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

当我使用 native 应用程序并使用UserCredentials时,它会验证用户,但如果我对 WebAPI 使用相同的方法,它会抛出异常

The request body must contain the following parameter: 'client_secret or client_assertion'

当我通过 clientCredentials 使用 WebAPI 时,它会生成 accessToken,但不会验证用户凭据。我还尝试在后续调用中将凭据作为 httpclient header 的一部分传递,尽管凭据错误,但它仍在工作。

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");

有没有一种方法可以在不使用 native 应用程序的情况下验证凭据?我认为 Graph API 并不是一个正确的选择。

最佳答案

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

The request body must contain the following parameter: 'client_secret or client_assertion'

我用头撞了一会儿,然后在 Twitter 上联系了 AzureSupport。

事实证明,仅当您将 Azure AD 应用程序设置为 native 客户端应用程序时,才支持这种类型的身份验证。如果将其设置为 Web 应用程序,则会收到该错误,因为访问 Azure AD 中的 Web 应用程序的唯一方法是通过客户端 ID + key 。

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

关于c# - 如何使用 Web 应用程序/WebAPI 验证 Azure AD 中的用户凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35462214/

相关文章:

c# - 离开 Activity 去另一个 Activity 时,Xamarin Android Finalizer 没有被调用

Azure 门户 - 无法创建 Signal R 服务

javascript - 动态显示所有页面的页面名称到index.html

javascript - Web Api 2 属性路由和 Angular JS 参数

C# 处理多个 if/else if 语句的更好方法

c# - ASP.Net-Core 选项验证

c# - 删除字符串的最后一个字符c#

azure - 使用 Next-Auth 身份验证从 Azure Active Directory 获取配置文件图像

azure - 从 tfs 预览部署到 Windows Azure 云服务时出错

c# - 'System.Web.Http.HttpConfiguration' 不包含 'EnableQuerySupport' 的定义