通过传递用户名和密码来获取jwt令牌的Azure广告身份验证

时间:2018-07-17 11:07:19

标签: azure azure-active-directory

当前,我正在尝试通过传递用户名和密码来实现azure活动目录身份验证。因此,为此,我尝试获取访问权限,但面临同样的问题。如果我使用客户端ID和客户端密钥,那么我能够获得令牌,但是当我尝试通过传递用户名和密码时,它不会给出结果并抛出异常: “ error”:“ invalid_client”,“ error_description”:“ AADSTS70002:请求正文必须包含以下参数:'client_secret或client_assertion'

在我为此使用的代码下面:

 /// <summary>
    ///     Working with client id and client secret
    /// </summary>
    /// <returns></returns>
    public async Task<string> GetTokenUsingClientSecret()
    {
        //authentication parameters
        string clientID = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
        string clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXX";
        string directoryName = "xxx.onmicrosoft.com";
        var credential = new ClientCredential(clientID, clientSecret);

        var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/" + directoryName, false);
        var result = await authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", clientCredential: credential);

        if (result == null)
        {
            throw new InvalidOperationException("Failed to obtain the JWT token");
        }
        string token = result.AccessToken;
        return token;
    }

    /// <summary>
    ///     Not Working with username and password.
    /// </summary>
    public async Task<string> GetTokenUsingUserNamePassword()
    {
        try
        {
            string user = "username.onmicrosoft.com";
            string pass = "yourpassword";
            string directoryName = "XXXX.onmicrosoft.com";
            string authority = "https://login.microsoftonline.com";
            string resource = "https://management.core.windows.net/";
            string clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

            var credentials = new UserPasswordCredential(user, pass);
            var authenticationContext = new AuthenticationContext($"{authority}/{directoryName}");
            var result = authenticationContext.AcquireTokenAsync(resource: resource, clientId: clientId, userCredential: credentials);

            return result.Result.AccessToken;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

1 个答案:

答案 0 :(得分:0)

  

AADSTS70002:请求正文必须包含以下参数:“ client_secret或client_assertion”。

根据您提到的例外情况,我假设您注册了一个Azure AD Web应用程序/ API应用程序。请尝试使用Azure AD本机应用程序,然后它应该可以工作。您可以参考本文档的更多详细信息-Constraints & Limitations section

  

没有网站/机密客户

     

这不是ADAL限制,而是AAD设置。您只能使用来自本机客户端的流。 机密客户端(例如网站)不能使用直接用户凭据

如何重新注册Azure AD本机应用程序。

enter image description here