如何通过powershell cmdlet获取身份验证令牌?

时间:2016-12-12 23:46:55

标签: c# powershell module cmdlet

我需要为我对API发出的请求添加身份验证承载。我在C#中完成了这个,但需要通过powershell来完成。我尝试将我的C#方法转换为这样的cmdlet:

[Cmdlet(VerbsCommunications.Get, "Token")]
public class GetAuthTokenCommand : Cmdlet
{
    // Overide the ProcessRecord method
    protected override void ProcessRecord()
    {
        AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/blablaguid/oauth2/token");
        Task<AuthenticationResult> resultTask = authContext.AcquireTokenAsync(
            "MyResourceUri",
            "MyClientId",
            new Uri("https://login.live.com/oauth20_desktop.srf"),
            new Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(PromptBehavior.Auto, false));

        resultTask.Wait();

        WriteObject("Token: "+ resultTask.Result.AccessToken);
    }
}

然而,这给了我一个错误:

+ CategoryInfo          : NotSpecified: (:) [Send-Greeting], AggregateException
+ FullyQualifiedErrorId : System.AggregateException,GetAuthtoken.SendGreetingCommand

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

function GetAuthToken
{
    param
    (
            [Parameter(Mandatory=$true)]
            $ApiEndpointUri,

            [Parameter(Mandatory=$true)]
            $AADTenant
    )
    $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
                "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    $adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
                    "Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

    [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
    [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
    $authorityUri = “https://login.windows.net/$aadTenant”

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri

    $authResult = $authContext.AcquireToken($ApiEndpointUri, $clientId,$redirectUri, "Auto")

    return $authResult
}

$ApiEndpointUri = "https://management.azure.com/" #change this to graph api uri
$AADTenant = 'GUID' #AAD tenant guid
$token = GetAuthToken -ApiEndPointUri $ApiEndpointUri -AADTenant $AADTenant
$header = @{
    'Content-Type'='application\json'
    'Authorization'=$token.CreateAuthorizationHeader()
}

$request = ``
(Invoke-RestMethod -Uri $request -Headers $header -Method Get).value

我之前从Web上的某个地方(不记得在哪里)用它来查询Azure REST \ Graph Api。