Microsoft Graph Authentication

2019-08-11 14:32发布

问题:

I’m building an application in Python which can retrieve data from Azure AD. This data can require either Application permissions or Delegated permissions. I had a success retrieving data which needs only Application permissions. However, in order to retrieve data which needs delegated permission, I am trying to use OAuth2. Is it possible to get authenticated with Microsoft Graph using OAuth2 but not having the user sign in using the web page, but instead supplying the user credentials through the Python script itself?

Note: I want to use Microsoft Graph API (v1.0 and beta) and not Azure AD Graph API.

回答1:

Yes, this is possible - but keep in mind that there are two Azure AD endpoints for application registration!

Try registering an application on the AAD V2.0 endpoint (apps.dev.microsoft.com), and then use a 'password' grant_type in your request.

Here are the steps you need: - Register your app on the AAD v2.0 endpoint, and generate a password (take note of this)
- Assign your required permissions (in this case, delegated) - As a callback URL I'd suggest using postman's Oauth2 callback URL first so you can debug what you're doing: https://www.getpostman.com/oauth2/callback - Important! If any of those permissions require admin consent, you MUST consent to them first to make the app available. This requires the admin user to sign in once.

Once consent has been given, here's what your request needs to get a bearer token: POST https://login.microsoftonline.com/common/oauth2/token Request body (x-www-form-urlencoded): grant_type=[password] username=[user email address] password=[user password] resource=https://graph.microsoft.com client_id=[your newly registered application ID] client_secret=[application password you noted during registration]

If successful, you'll get the bearer & refresh token as a response.

Hope this helps,

Ben



回答2:

You need an Azure AD application to be able to authenticate with Graph API. A native Azure AD app and the flow and considerations described here work for ADAL.net. I use it to provision Microsoft Teams unattended: http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

I guess for Python you should have a look at ADAL for Python: https://github.com/introp-software/azure-activedirectory-library-for-python-old/blob/master/README.md

I think that the username/password auth is only possible with a native Azure AD app and not the web/web api types.