我有一个 Azure AD 应用程序注册,用于使用证书连接到 SharePoint。我想测试 api 调用,为此我使用 PostMan。要在 PostMan 中使用证书进行测试,我需要使用客户端断言。
如何从我的 PFX 文件轻松生成 JWT 令牌? 我找到了这个 PowerShell,但无法让它工作。 PS5 或 PS7 都没有
$x509cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($CertificatePath_Pfx, $CertPassWord)
$signingX509Certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($CertificatePath_Pfx, $CertPassWord, 'Export')
$claims = new-object 'System.Collections.Generic.Dictionary[String, Object]'
$claims['aud'] = $aud
$claims['iss' ] = $ClientId
$claims['sub'] = $ClientId
$claims['jti'] = [GUID]::NewGuid().ToString('D')
#$signingCredentials = [Microsoft.IdentityModel.Tokens.X509SigningCredentials]::new($x509cert)
$signingCredentials = New-Object -TypeName Microsoft.IdentityModel.Tokens.X509SigningCredentials($signingX509Certificate)
$securityTokenDescriptor = [Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor]::new()
$securityTokenDescriptor.Claims = $claims
$securityTokenDescriptor.SigningCredentials = $signingCredentials
$tokenHandler = [Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler]::new()
$clientAssertion = $tokenHandler.createToken($securityTokenDescriptor)
write-host $clientAssertion
我收到以下错误:
New-Object : Exception calling ".ctor" with "1" argument(s): "The type initializer for 'PerTypeValues`1' threw an excep
tion."
At C:\temp\certs\GetClientAssertion.ps1:50 char:24
+ ... edentials = New-Object -TypeName Microsoft.IdentityModel.Tokens.X509S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
在此行:
$signingCredentials = New-Object -TypeName Microsoft.IdentityModel.Tokens.X509SigningCredentials($signingX509Certificate)
在 PowerShell 中生成令牌的一种简单方法是使用 PowerShell MSAL 模块。
安装模块:
Install-Module MSAL.PS
代码示例:
Import-Module MSAL.PS
$pfxPath = "C:\mycert.pfx"
$pfxPwd = "p@ssw0rd!"
$clientId = ""
$tenantId = ""
$clientCertificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($pfxPath, $pfxPwd)
$token = Get-MsalToken -ClientId $clientId -ClientCertificate $clientCertificate -TenantId $tenantId -ForceRefresh -Scope $scope
$jwt = $token.accesstoken