Microsoft Graph身份验证

问题描述:

我正在用Python构建一个应用程序,该应用程序可以从Azure AD检索数据.此数据可能需要应用程序"权限或委派"权限.我成功检索了仅需要应用程序权限的数据.但是,为了检索需要委托权限的数据,我尝试使用OAuth2.是否可以使用OAuth2通过Microsoft Graph进行身份验证,但不让用户使用网页登录,而是通过Python脚本本身提供用户凭据?

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?

注意:我要使用Microsoft Graph API(v1.0和beta),而不要使用Azure AD Graph API.

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

是的,这是可能的-但请记住,有两个用于应用程序注册的Azure AD终结点!

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

尝试在AAD V2.0终结点(apps.dev.microsoft.com)上注册应用程序,然后在您的请求中使用密码" grant_type.

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

以下是您需要执行的步骤: -在AAD v2.0端点上注册您的应用,并生成密码(以 请注意)
-分配所需的权限(在这种情况下,是委派的) -作为回调URL,我建议您首先使用邮递员的Oauth2回调URL,以便您可以调试正在执行的操作: https://www.getpostman.com/oauth2/callback - 重要的!如果这些权限中的任何一个需要管理员同意,则必须首先同意他们才能使该应用程序可用.这要求管理员用户登录一次.

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.

一旦获得同意,这就是您的请求需要获得不记名令牌的条件: POST https://login.microsoftonline.com/common/oauth2/token 请求正文(x-www-form-urlencoded): grant_type = [密码] 用户名= [用户电子邮件地址] 密码= [用户密码] resource = https://graph.microsoft.com client_id = [您新注册的应用程序ID] client_secret = [您在注册时记下的应用程序密码]

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,