首页 > 解决方案 > 如何使用 c# 针对 Azure AD 验证用户密码

问题描述

我正在尝试使用用户名和密码获取令牌,但身份验证抛出异常并且令牌为 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);
                }

            }

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

标签: c#azureactive-directoryazure-active-directoryazure-ad-graph-api

解决方案


此代码没问题。您需要检查 Azure 门户中的配置。

1.将您的应用程序视为公共客户端。

在此处输入图像描述

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

在此处输入图像描述


推荐阅读