在 Powershell 中生成带有 X.509 证书签名的 JWT

Generate a JWT with an X.509 certificate signature in Powershell

我正在尝试使用证书身份验证从 Active Directory 获取 API 访问令牌,如下所示:

Access token request with a certificate

请求需要 client_assertion 属性,它是从证书创建的 JWT,格式和规格在这里提到:

Assertion format

是否有一种在 Powershell 中生成非交互式令牌的方法,因为这是发布管道的一部分?

编辑:为了让它更清楚一点,这个使用 Microsoft.IdentityModel.Clients.ActiveDirectory 库的 C# 代码是我在 Powershell 中尝试做的,特别是第二个行:

AuthenticationContext authContext = new AuthenticationContext(authority);

IClientAssertionCertificate assertion = new ClientAssertionCertificate(clientId, certificate);

authenticationResult = await authContext.AcquireTokenAsync(resource, assertion);

据我所知,您无法使用 PowerShell 创建 JWT。

您可以使用 jwt.io 编辑每个部分(header,有效负载),然后 jwt.io 会自动将其编码为 client_assertion 的 JWT。

示例代码(刚刚测试过,当我将应用程序注册为 Web 应用程序时这对我有用)。

<#
    Sample to connect to Graph using a certificate to authenticate

    Prerequisite : ADAL (Microsoft.IdentityModel.Clients.ActiveDirectory.dll)

#>

# Load the ADAL Assembly
Add-Type -Path "E:\Assemblies\Microsoft.IdentityModel.Clients.ActiveDirectory.4.3.0\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"

# Settings for the application
$AppID = '<ID OF THE WEB APP>'
$TenantDomain = '<TENANT>'
$LoginUri = 'https://login.microsoftonline.com/'
$Resource = 'https://graph.microsoft.com'
$Certificate = Get-Item 'Cert:\CurrentUser\My\<CERTIFICATE THUMBPRINT>' # This points to my own certificate

# Auth Authority Uri
$Authority = "$LoginUri/$TenantDomain"
# Create the authenticationContext
$Context = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($Authority)
# create the CAC
$CAC = [Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate]::new($AppID,$Certificate)
# Get the token
$TokenResponse = $Context.AcquireTokenAsync($Resource,$CAC)

Start-Sleep -Seconds 1 # Sleep for 1 second...

# Token should be present
$TokenResult = $TokenResponse.Result