【问题标题】:How to create Client Assertion JWT token when connecting to Azure AD?连接到 Azure AD 时如何创建客户端断言 JWT 令牌?
【发布时间】:2021-08-13 13:56:43
【问题描述】:

我的问题是,在将授权代码发送回 Azure AD 以获取访问令牌时,我不确定使用什么来签署 JWT 令牌以进行客户端断言。支持的身份验证方法是“private_key_jwt”。唯一提供的是 client_id、tenant_id 和清单文件端点。

【问题讨论】:

  • 您需要一个证书,并且它的公钥需要上传到 AAD 应用注册密钥。请查看github.com/AzureAD/microsoft-authentication-library-for-python,我没有使用python版本,但它可能会使您的过程更容易。
  • 谢谢,这很有帮助。只有一件事,什么样的证书,是 SSL 还是针对这种特定情况生成的证书? @juunas
  • 本案证明。

标签: python django azure oauth-2.0 openid


【解决方案1】:

要完成整个过程,我们应该首先创建证书。我在这里使用自签名证书进行演示。

第 1 步:创建 .cer 和 .key 文件,我们将 .cer 上传到 Azure AD App 并使用 .key 文件签署我们的 JWT 令牌。

1)通过Powershell创建一个密码为123456的自签名证书:

$cert = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname stantest.com
$pwd = ConvertTo-SecureString -String '123456' -Force -AsPlainText
$path = 'cert:\localMachine\my\' + $cert.thumbprint 
Export-PfxCertificate -cert $path -FilePath <path of your pfx file> -Password $pwd

2)在CMD中根据.pfx文件创建.cer文件:

openssl pkcs12 -in <path of .pfx file> -clcerts -nokeys -out <path of .cer> 

3)在CMD中根据.pfx文件创建.key文件:

openssl pkcs12 -in <path of .pfx file> -nocerts -nodes  -out <path of .pem file>
openssl rsa -in <path of .pem file> -out <path of .key file>

最后,我们将获得以下文件:

第 2 步:将 .cer 文件上传到您的 Azure AD 应用并记下其指纹值:

第 3 步:使用下面的 python 代码签署 JWT 并为 Microsoft Graph API 交换访问令牌(确保您的应用已被授予列出用户的权限):

import sys 
import json
import logging

import requests
import msal

config = {
    "client_id":"your application ID here",
    "authority":"https://login.microsoftonline.com/Your tenant name or ID",
    "thumbprint":"cert thumbprint value in step2",
    "private_key_file":r"the path of .pem file of private key",
    "scope": ["https://graph.microsoft.com/.default"],
    "endpoint":"https://graph.microsoft.com/v1.0/users?$top=1"
}


app = msal.ConfidentialClientApplication(
    config["client_id"], authority=config["authority"],
    client_credential={"thumbprint": config["thumbprint"], "private_key": open(config['private_key_file']).read()},
    )


result = app.acquire_token_for_client(scopes=config["scope"])

if "access_token" in result:
    print("Access Token value: " + result['access_token']);
    # Calling graph using the access token
    graph_data = requests.get(  # Use token to call downstream service
        config["endpoint"],
        headers={'Authorization': 'Bearer ' + result['access_token']},).json()
    print("Graph API call result: %s" % json.dumps(graph_data, indent=2))
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))  # You may need this when reporting a bug

结果:

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2016-12-02
    • 1970-01-01
    • 2019-04-10
    • 2015-10-04
    • 2019-10-27
    • 2020-01-31
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多