本文介绍了使用python的MS Graph身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试编写Python代码,以访问我的日历并检索我的日程安排.无法通过身份验证阶段.看到并测试了许多示例,但是所有示例都需要运行本地服务器,在本地浏览我需要单击一个按钮,然后输入我的凭据.旨在在我的Python代码中执行所有这些操作.

Trying to write a Python code where I would like to access my calendar and retrieve my schedule.Not able to get through the authentication phase.Seen and tested many examples, but all require running a local server where I browse locally and need to click a button and then enter my credentials.Aiming to perform all of this inside my Python code.

推荐答案

您可以通过以下两种方法之一来实现:

You can achieve this one of two ways:

  1. 使用资源所有者密码凭据流-这使您可以将用户名和密码传递给Azure AD.麻烦的是,如果身份验证流程上还有其他任何东西(同意,MFA,密码重置),您只会失败.
  2. 使用客户端凭据流-这需要管理员同意.另外,您必须非常小心这一点,因为此客户端将有权访问有关所有用户的所有信息.只能用于安全客户端,不能用于其他用户有权访问的客户端.
  1. Using Resource Owner Password Credential flow - This allows you to pass the username and password to Azure AD. Gotcha's here are if there's any extra thing on the auth flow (consent, MFA, password reset) you'll just get a failure.
  2. Using Client Credentials flow - This one requires admin consent. Also, you have to be really careful about this one as this client will have access to ALL info about all users. This should only be used with secure clients, not clients that other users have access to.

下面是展示这两个代码的代码段:

Here's a code snippet that showcases both of these:

import adal
import requests

tenant = "contoso.com"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"

username = "[email protected]"
password = "mypassword"

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_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}

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

这篇关于使用python的MS Graph身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:10