取得Microsoft Graph API 验证 token - MSAL

说明

继上篇建立 App Registration 後,本篇将继续介绍使用MSAL透过Activate Directory取得API存取授权token。下列说明一样使用Jupyter Notebook操作并记录,可参考文件。

MSAL

使用前先安装套件

pip install msal

接下来需要读取一些资讯,这边我是记在env档案,再从程序中读取:

import os
from dotenv import load_dotenv
import msal
import logging

load_dotenv()
authority = os.environ["AUTHORITY"]                      ##https://login.microsoftonline.com/{TENANT ID}
client_id = os.environ["CLIENT_ID"]                      ##ENTER THE CLIENT ID OF YOUR SERVICE PRINCIPAL
client_secret = os.environ["CLIENT_SECRETE"]             ##ENTER THE CLIENT SECRET OF YOUR SERVICE PRINCIPAL

其中CLIENT_ID及AUTHORITY中所需的TENANT ID可在下图中红框的位置取得。

image-20201014163008896

CLIENT_SECRETE则是到Certificates & secrets建立新的(或是有记得之前建立且尚未过期的也行),按一下复制即可。

建立後重新整理CLIENT_SECRETE就会隐藏,所以要记下来,不然下次还要再建一次新的。

image-20201014163225153

接着执行以下程序码。下列程序码为回传取得graph api 的token内容,并显示token类型。若成功取得的话,会显示Bearer,表示取得的token为Bearer型态,而token就在result['access_token']中。

app = msal.ConfidentialClientApplication(
    client_id, authority=authority,
    client_credential=client_secret)

# The pattern to acquire a token looks like this.
result = None

# First, the code looks up a token from the cache.
# Because we're looking for a token for the current app, not for a user,
# use None for the account parameter.
result = app.acquire_token_silent(["https://graph.microsoft.com/.default"], account=None)

if not result:
    logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
    result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])

if "access_token" in result:
    # Call a protected API with the access token.
    print(result["token_type"])
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))  # You might need this when reporting a bug.

总结

有了token之後,就可以在权限许可范围中,在header中加入Bearer token使用Microsoft Graph API,详细内容无法在本次铁人赛中一一说明,可以到这里欣赏。


Amos3.0 团队系列文

以下为团队所有成员的主题,也欢迎大家前往欣赏喔!


<<:  [JS] You Don't Know JavaScript [Scope & Closures] - Limiting Scope Exposure ?

>>:  Day30 最後的拼图 - 音效篇

Day 3 : 案例分享(1.1) -B2C经典流程 电子商务、POS + 进销存 + 会计(应收付) +制造(产品组合、产品转换)

案例前情提要 会想来使用Odoo的公司,通常是在市面上现有ERP系统找不到解决方案的公司,归纳一下 ...

[Day 14 - 小试身手] 用HTML、CSS、JS打造个人网站 (1)

所有的网站大概可以分成两类:静态网页、动态网页,静态网页顾名思义就是静止的网页,不会去太频繁的更新内...

Day 16 - 用 useReducer 取代 Redux !?

如果有错误,欢迎留言指教~ Q_Q useReducer 看起来跟 Redux 的 reducer...

Day17

arrary很别好理解,一维arrary就是线,二维arrary就是面,三维arrary就是立方体,...

IDS 的检测阈值(The detection threshold of IDS)

混淆矩阵中的敏感性是评估 IDS 性能的常用方法。 .一旦 IDS 发送警报,就应该对其进行调查和验...