使用python requests和MSAL进行身份验证
项目描述
使用python requests和MSAL进行身份验证。这使用MSAL缓存重复请求。
错误/问题
用法
兼容性
设备代码流
自版本0.2.0起:无头
自版本0.6.0起:MSAL_REQUESTS_AUTH_HEADLESS环境变量
自版本0.7.0起:KeyringTokenCache
import requests
import msal
from msal_requests_auth.auth import DeviceCodeAuth
from msal_requests_auth.cache import KeyringTokenCache
client_id = "<client ID from Azure AD>"
tenant_id = "<tenant ID from Azure AD>"
application_id = "<client ID of application you want to get a token for from Azure AD>"
with KeyringTokenCache() as token_cache:
app = msal.PublicClientApplication(
client_id,
authority=f"https://login.microsoftonline.com/{tenant_id}/",
token_cache=token_cache,
)
auth = DeviceCodeAuth(
client=app,
scopes=[f"{application_id}/.default"],
)
response = requests.get(
endpoint,
auth=auth,
)
客户端凭据流
import requests
import msal
from msal_requests_auth.auth import ClientCredentialAuth
client_id = "<client ID from Azure AD>"
client_secret = "<client secret for client in Azure AD>"
tenant_id = "<tenant ID from Azure AD>"
application_id = "<client ID of application you want to get a token for from Azure AD>"
app = msal.ConfidentialClientApplication(
client_id,
authority=(f"https://login.microsoftonline.com/{tenant_id}/"),
client_credential=client_secret,
)
auth = ClientCredentialAuth(
client=app,
scopes=[f"{application_id}/.default"],
)
response = requests.get(
endpoint,
auth=auth,
)
安装
要安装msal-requests-auth,请在您的终端中运行此命令
$ python -m pip install msal_requests_auth
如果您使用conda
$ conda install -c conda-forge msal_requests_auth
Windows密钥环后端
Windows凭证存储器默认由keyring使用。然而,其密码长度限制通常会导致令牌无法存储。一个替代的后端可能可以解决这个限制。在选择后端时,请确保您了解其限制。
请考虑使用keyrings.alt作为替代的keyring后端。
python -m pip install keyrings.alt
以下是如何为keyring设置替代后端的一个示例。
import keyring
keyring.core._config_path().parent.mkdir(parents=True, exist_ok=True)
keyring.core._config_path().write_text(
"[backend]\ndefault-keyring=keyrings.alt.Windows.EncryptedKeyring"
)
致谢
本软件包是用Cookiecutter和audreyr/cookiecutter-pypackage项目模板创建的。
项目详情
关闭
msal_requests_auth-0.8.1.tar.gz的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 67609d6591b2842430b4def56a4ceff512a3ef495c7ab678180603345947f55d |
|
MD5 | ad8c6d6d3118c57871fbc7076c2745f9 |
|
BLAKE2b-256 | 6f62b80be77015c7d28c322666a3e9986fc919e94c84ff2f50b29412f4666bba |
关闭
msal_requests_auth-0.8.1-py3-none-any.whl的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | c6965d5973ecdf4ddfd5c723413b42792a257d6f8600fb29bfd48a5c613055eb |
|
MD5 | 546cc222e54d2989488b358aa65d3d1a |
|
BLAKE2b-256 | 8d4cbe6a7bb039b91d12aaeb0098d1b00f77df589436adefe58b81ebe70e1558 |