如何使用 c# 对 Azure AD 的用户密码进行身份验证

How to Authenticate Pasword of User against Azure AD using c#

我正在尝试使用用户名和密码获取令牌,但身份验证抛出异常并且令牌为 NULL。我是 Azure 的新手。我的代码:

 public string AuthenticateUser(string username, string password)
    {
        const string resources = "https://management.core.windows.net/";
        const string clientId = "";
        const string aadTokenIssuerUri = "https://login.windows.net/common/";
        AuthenticationContext authenticationContext = new AuthenticationContext(aadTokenIssuerUri);
        UserCredential userCredentials = new UserPasswordCredential(username, password);
        if (authenticationContext.TokenCache != null)
        {
            authenticationContext.TokenCache.Clear();
        }
        AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(
            resources,
            clientId,
            userCredentials).GetAwaiter().GetResult();
        var token = authenticationResult.AccessToken;
        return token;

}

          try
            {
                var token =   azureUsers.AuthenticateUser("", "");
                if (!string.IsNullOrEmpty(token))
                {
                    Console.WriteLine("here is token {0}", token);
                   result = true;
                }
            }
            catch (Exception e)
            {
                if (i < numRetries)
                {
                    Thread.Sleep(retryInterval);
                }

            }

请告诉我这段代码有什么问题。

此代码 fine.You 需要检查 Azure 门户中的配置。

1.Treat 您作为 public 客户的申请。

2.Add Azure 服务管理 api 权限并授予 admin/user 同意(此用户和资源的交互式授权请求。)