# 用管理员身份打开PowerShell
$cert = New-SelfSignedCertificate `
-CertStoreLocation Cert:\LocalMachine\My `
-DnsName "identityplatform.xizhang.com" `
-KeyExportPolicy Exportable `
-Provider "Microsoft Enhanced RSA and AES Cryptographic Provider"
# 导出证书公钥(用于上传到Azure)
Export-Certificate -Cert $cert -FilePath C:\temp\identityplatform.cer
# 导出证书私钥(用于在其他电脑上安装)
$pwd = ConvertTo-SecureString -String "xxxx" -AsPlainText -Force
Export-PfxCertificate -Cert $cert -FilePath c:\temp\identityplatform.pfx -Password $pwd
Install-Module -Name MSAL.PS -Scope CurrentUser
# MSAL.PS 不是官方库,但也是由微软员工编写的
$token= Get-MsalToken `
-ClientId 85e5dba4-9cad-4191-87e2-c75ab83c957e `
-TenantId 3a6831ab-6304-4c72-8d08-3afe544555dd `
-ClientSecret (ConvertTo-SecureString `
"MtQ7Q~hJpoaXFzyZBoBUnvhK7X~U-mLRngZ7N" `
-Force -AsPlainText)
# 或用证书
$token= Get-MsalToken `
-ClientId 85e5dba4-9cad-4191-87e2-c75ab83c957e `
-TenantId 3a6831ab-6304-4c72-8d08-3afe544555dd `
-ClientCertificate `
(Get-ChildItem `
"Cert:\LocalMachine\My\A639157B5BBC31DC007CC014B077F8D70A082122")
# 安装sdk
# pip install msal
from msal import ConfidentialClientApplication
client_id = "85e5dba4-9cad-4191-87e2-c75ab83c957e"
authority = "https://login.microsoftonline.com/3a6831ab-6304-4c72-8d08-3afe544555dd"
client_secret = "MtQ7Q~hJpoaXFzyZBoBUnvhK7X~U-mLRngZ7N"
app = ConfidentialClientApplication(client_id, client_secret, authority)
token = app.acquire_token_for_client("https://graph.microsoft.com/.default")
WSL
)openssl pkcs12 -in identityplatform.pfx -out out.pem -nodes
# 以下的private key信息只是范例
key ="""-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAVZpqBeRFQCfq
VhQM9/W8BtBu/w1my+jfdMUSyQ==
-----END PRIVATE KEY-----"""
client_certificate ={
"private_key":key,
"thumbprint":"A639157B5BBC31DC007CC014B077F8D70A082122"
}
app = ConfidentialClientApplication(client_id,client_certificate,authority)
token = app.acquire_token_for_client("https://graph.microsoft.com/.default")
你可以通过邮件 ares@xizhang.com 与我取得联系,也可以关注 code365xyz
这个微信公众号给我留言。
点击这里 或扫码可以访问配套视频教程。
陈希章 2022年2月 于上海
MtQ7Q~hJpoaXFzyZBoBUnvhK7X~U-mLRngZ7N