Acquire Token by service account with MSAL

933 views Asked by At

we are using ADAL to acquire tokens by a service account silently (no prompt, no redirect). This is our sample code:

var clientId = "";
var tenantDomain = "";
var userName = "";
var password = "";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantDomain));
var credential = new UserPasswordCredential(userName, password);
var result = await context.AcquireTokenAsync("https://management.core.windows.net/", clientId, credential);

How can I acquire tokens using MSAL?

2

There are 2 answers

0
BrunoLucasAzure On BEST ANSWER

I haven't used this type of authentication in a long time since this is no longer encouraged to be used.

you would also need to set your app reg like this and seems like this option is gone: enter image description here

code sample

try
            {
                var securePassword = new SecureString();
                foreach (char c in "yourpassword")        // you should fetch the password
                    securePassword.AppendChar(c);  // keystroke by keystroke

                result = await app.AcquireTokenByUsernamePassword(scopes,"[email protected]", securePassword).ExecuteAsync();


            }
            catch (Exception ex)
            {
                // See details below
            }

You may want to replace it with an SPN secret auth: https://learn.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token

0
StefanFFM On

Use AcquireTokenByUsernamePassword(), see MSDN.

Note that usage of this flow is discouraged as it requires you to handle passwords in your code.