Search code examples
pythonazureaccess-token

Azure graph api returning different token each time a login attempt is made.?


I have a python api which accepts email and password from a login webpage. This email and password is used to login to azure ad and in response we get a access token which is valid for 1hr. Below is the sample python code:

context = adal.AuthenticationContext(config_data['AUTHORITY_HOST_URL'] + '/' + config_data['TENANT'], validate_authority="cceaddik-1q7c5-997ad-6453-sduf9347asit8" != 'adfs')

token = context.acquire_token_with_username_password(config_data['RESOURCE'], email, password, config_data['CLIENT_ID'])

print(token['accessToken'])

Normally this token generated for a user should be valid for 1hr and if same user is logging again within the same 1hr, it should get the same access token. But what I have noticed is that, each time we login, we are getting different access token. Why is this happening. Can anyone please throw some lights on it. Thanks.


Solution

  • You will always get a new token when you call Azure AD. It does not cache tokens there. A token is valid for one hour from the time you requested the token.

    As a side note, handling passwords is a bad idea in general. It would be much better to use one of the interactive login flows like authorization code flow. You cannot enable MFA for users for example, as the login would fail.