2

I'm following this link> python-sample-send-mail to send email, but I would like to skip or authenticate the user on background without any UI interaction. I don't like the idea that OAuth: pop up a window.

My application is registered in Microsoft Azure AD.

I would like to know how to authenticate with a Email username and a password without UI interaction.

Thanks a lot!

1
  • The purpose of OAuth is to securely authenticate a user via username/password. Hardcoding these into an application is a substantial security hole and really shouldn't be done. Commented Jul 30, 2018 at 15:16

1 Answer 1

2

Based on the doc:AAD V2.0 end pointRestrictions on protocols ,The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint.

In python ADAL sdk , client secret is not accepted by acquire_token_with_username_password method, so you need to register native app.

Sample code:

import adal
import requests

tenant = ""
client_id = "app id"
# client_secret = ""

username = ""
password = "”

authority = "https://login.microsoftonline.com/" + tenant
RESOURCE = "https://graph.microsoft.com"

context = adal.AuthenticationContext(authority)

# Use this for Client Credentials
#token = context.acquire_token_with_client_credentials(
#    RESOURCE,
#    client_id,
#    client_secret
#    )

# Use this for Resource Owner Password Credentials (ROPC)
token = context.acquire_token_with_username_password(RESOURCE, username, password, client_id)

graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}'

# /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/
request_url = graph_api_endpoint.format('/me')
headers = {
'User-Agent' : 'python_test',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}

response = requests.get(url = request_url, headers = headers)
print (response.content)

In addition, native app is not necessary if you use REST API, but client secret need to be set.

enter image description here

Hope it helps you.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Jay! I will try, also now I am able to send a email via postman and my app now is classified as Web app / API in portal azure. I followed the flow 2 of this precious article [codematters.tech/… (codematters.tech/…) that made me able to send a email, write the request that I did in postman will be pretty straightforward in python.
@Luis L Hi,if you think my answer is useful,you could mark it for answer. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.