簡體   English   中英

如何使用 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);
                }

            }

請告訴我這段代碼有什么問題。

這段代碼沒問題。需要在Azure 門戶中檢查配置。

1.將您的應用程序視為公共客戶端。

在此處輸入圖片說明

2.添加 Azure 服務管理 api 權限並授予管理員/用戶同意(對此用戶和資源的交互式授權請求。)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM