如何使用c#根据Azure AD验证用户的密码

问题描述 投票:0回答:1

我正在尝试使用用户名和密码获取令牌,但是身份验证抛出异常,令牌为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# azure active-directory azure-active-directory azure-ad-graph-api
1个回答
0
投票

此代码很好。您需要在Azure门户中检查配置。

1。作为公共客户端处理您的应用程序。

enter image description here

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.