微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

连接到Azure AD时如何创建客户端声明JWT令牌?

如何解决连接到Azure AD时如何创建客户端声明JWT令牌?

我的问题是,当将授权代码发送回Azure AD以获取访问令牌时,我不确定用于签名JWT令牌以进行客户端声明的方式。支持的身份验证方法是“ private_key_jwt”。唯一提供的是client_id,tenant_id和清单文件端点。

解决方法

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

步骤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>

最后,我们将在下面获取文件: enter image description here

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

enter image description here

第3步:使用下面的nodejs代码对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

结果: enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。