Search code examples
pythonazureauthenticationazure-active-directoryadal

Unable to auth as user programmatically


I'm using the following code (python, but it doesn't really matter, getting the same result with powershell and invoke-webrequest):

from msrestazure.azure_active_directory import UserPassCredentials
username = '%username%'
password = '%password%'
client_id = '{Azure AD Application GUID}'
secret_id = '{Azure AD Application secret}'
credentials = UserPassCredentials(username, password, client_id, secret_id)

this works for users in one tenant, but doesn't work for the users from another tenant with a weird error:

msrest.exceptions.AuthenticationError: , InvalidGrantError: (invalid_grant) AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password

I can login using the portal with the same credentials just fine. The tenant in question is using AAD Sync and SSO, could that interfere?

If yes, how do I obtain tokens for the users in such an Azure AD?


Solution

  • I am pretty sure understand the serious security implications of using the Resource owner password credential grant when try to login with Azure AD.

    There are also a couple of issues/side effects with it:

    • If your account is MFA / Conditional Access enabled, then you won't be to login using the resource owner password credential grant. Period. There is no way.
    • If your domain is federated (like in your case), you won't be able to login. There is a slight chance, that it would be possible to login, if you also do Password Hash Sync, but I am not sure whether this would help.

    At the end, the best way to authenticate a back-end-and-non-user-interactive process, is by using Service Principal.

    Check out the following documentation sources to learn more about service principals in Azure AD and how authenticate using a service principal: