简体   繁体   中英

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

I am trying to get token with username and password but Authentication is throwing exception and token is NULL . I am pretty new to Azure. My code :

 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);
                }

            }

Please tell me what is wrong with this code.

This code is fine.You need to check the configuration in Azure portal.

1.Treat your application as a public client.

在此处输入图片说明

2.Add Azure Service Management api permission and grant admin/user consent(interactive authorization request for this user and resource.)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM