Home > Back-end >  Passing Header Auth Bearer token as variable in Powershell Invoke-RestMethod
Passing Header Auth Bearer token as variable in Powershell Invoke-RestMethod

Time:06-18

I have the below code, where i am trying to capture the access token and passing it as a variable in the Headers section for Bearer token, but looks like the $Token.access_token is not getting replaced with in the header and i am getting below error.

ANy help would be highly appreciated

Invoke-RestMethod : {"error":"Unauthorized","message":"Failed to create session using the supplied Authorization header"}
At E:\restcurl.ps1:48 char:1
  Invoke-RestMethod -Uri $Uri -Headers $Headers -Method Post -ContentTy ...
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
     FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
PS E:\>
    Do {
    $RequestAccessTokenUri = "https://anypoint.mulesoft.com/accounts/api/v2/oauth2/token"
    $ClientId = "44b1d81339c74"
    $ClientSecret = "c3804f9fc18"   
    $auth_body = "grant_type=client_credentials&client_id=$ClientId&client_secret=$ClientSecret"

    $Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $auth_body -ContentType 'application/x-www-form-urlencoded'
    echo $Token.expires_in
    echo $Token.access_token    
    if ($Token.expires_in -gt 200) {  break }     
  } Until ($Token.expires_in -gt 200) 

  $path = 'E:\actions-runner\cuments-v1-1.0.2.jar';
  $jsonpath='E:\curljson.json'
  $Headers = @{
   'X-ANYPNT-ENV-ID' =  '4af1b64'
   'X-ANYPNT-ORG-ID' = 'c659234ad'
   'Authorization' =  "`"Bearer $Token.access_token`""
} 

CodePudding user response:

Assigning the token to a variable and passing it to the header helped

CodePudding user response:

I can see that you've resolved your issue by assigning the token to a variable and then passing that to the header.

It's also possible to use the PowerShell Subexpression operator $() in this instance.

The Subexpression operator is described as:

Returns the result of one or more statements. For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression.

This would essentially have transformed your Header code from:

$Headers = @{
   'X-ANYPNT-ENV-ID' =  '4af1b64'
   'X-ANYPNT-ORG-ID' = 'c659234ad'
   'Authorization' =  "`"Bearer $Token.access_token`""
} 

to:

$Headers = @{
   'X-ANYPNT-ENV-ID' =  '4af1b64'
   'X-ANYPNT-ORG-ID' = 'c659234ad'
   'Authorization' =  "`"Bearer $($Token.access_token)`""
} 

Wrapping $Token.access_token in the Subexpression operator $() causes PowerShell to evaluate this first and then return the resulting object/string to the caller.

  • Related