在Powershell

时间:2018-11-09 05:58:15

标签: powershell active-directory jwt azure-active-directory x509certificate

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

Access token request with a certificate

请求需要 client_assertion 属性,该属性是根据证书创建的JWT,其格式和规格如下:

Assertion format

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

编辑:为了更加清楚一点,我正在Powershell中尝试使用 Microsoft.IdentityModel.Clients.ActiveDirectory 库的C#代码,特别是第二行: / p>

AuthenticationContext authContext = new AuthenticationContext(authority);

IClientAssertionCertificate assertion = new ClientAssertionCertificate(clientId, certificate);

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

2 个答案:

答案 0 :(得分:1)

据我所知,您不能使用PowerShell创建JWT。

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

enter image description here

答案 1 :(得分:1)

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

<#
    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