API GET Request works fine with curl, but with powershell not - powershell

Good afternoon,
If I send this curl request via a command line it works fine. But when I use my powershell script I don't get the same result.
CURL script:
CURL --request GET "https://staging.tiptrack.nl/Tiptrack.Employer.Api/odata/EmployeeBudgets?$expand=Employee($expand=SecureEmployee)&$top=5" -H "accept: application/json" -H "Authorization: Bearer token"
Powershell script:
#------- Opvragen token tiptrack -------
#Dit is de URL waar de token voor tiptrack wordt opgevraagd.
$Url_token="https://tiptracknext-staging-login.indicia.nl/oauth2/aus342go9hNphcHXM0i7/v1/token"
#Dit is de body die mee wordt gestuurd in de request, deze informatie staat gelijk aan de data in de post request vanuit de handleiding.
$Data_token = #{
grant_type="client_credentials"
client_id="123456"
client_secret="123456"
scope="api"
}
$token_tiptrack=Invoke-RestMethod -Method Post -Uri $Url_token -ContentType "application/x-www-form-urlencoded" -Body $Data_token
#------- Opvragen Employerbudgetsid -------
#Dti is de URL waarna de GET request wordt gestuurd om het employerid te kunnen.
$Url_budgetid="https://staging.tiptrack.nl/Tiptrack.Employer.Api/odata/EmployeeBudgets?$expand=Employee($expand=SecureEmployee)&$top=5"
#Dit is header die mee wordt gestuurd in de request. Deze data in deze header staat gelijk aan de data in de API handleiding.
$header_process = #{
Authorization='Bearer '+$token_tiptrack.access_token
"accept"="application/json"
}
#Vanuit het uploaden van het bestand krijgen we een reactie van de server, in deze reactie staat het upload id, deze id hebben we nodig om het bestand te kunnen verwerken.
Invoke-RestMethod -Uri $Url_budgetid -Method Get -Headers $header_process | Select-Object -ExpandProperty value
I hope someone can help me with this problem. With the CURL action i get the first 5 rows and by powershell i get all avilible rows.

To pass a string value as verbatim or literal, it is favorable to use single quotes or backtick escape PowerShell's special characters. If you have no variable references within a string, single quotes is easiest.
# Using Single Quotes
$Url_budgetid='https://staging.tiptrack.nl/Tiptrack.Employer.Api/odata/EmployeeBudgets?$expand=Employee($expand=SecureEmployee)&$top=5'
# Escaping the $ while using double quotes
$Url_budgetid="https://staging.tiptrack.nl/Tiptrack.Employer.Api/odata/EmployeeBudgets?`$expand=Employee(`$expand=SecureEmployee)&`$top=5"
Using double quotes to surround a string makes the string expandable. When the code is run $ followed by legal variable name characters will be interpreted as variable references. In your session, $expand and $top would be substituted for their values, which would be $null if you had not defined them. As a result, it appears those strings are removed from the URI. You can see this happening just by typing $Url_budgetid at the console.

Related

LinkedIn API Share Content with symfony return 403

I want to connect one app to linkedin in order to share content for a company page. I use symfony 5.4 in order to.
I do the following step:
create a code : ok
create a token : ok
get user credential with the token : ok
I send this request:
yes here is the response I get :
TraceableHttpClient->request('POST', 'https://api.linkedin.com/v2/ugcPosts', array('headers' => array('Authorization: Bearer AQWkl2rmtRNpKP6ir_n_y7GloBnUJI--gp6hy0xxxxxxx-xxxxx-xxxxx-LedwHSBHATYSN3878kPadWjVH9Fm-_NdDnEau0rpElZe2C4UglKTpFFZDIs2tpT1o1N_oYjWwl6AmaduaG_1v-ZS76BKrR2RLxhvDhBaqTA9U_kIWleQPpRfV_hYGYZn5ILHbSOw6PnfxFo_3UulB-8QyyeS00W8l1pAKr3cVpqxsDhfPFYZLazIGFePfaEFxlqEqZsJjSrj1jUewejLzdojs8gqcqY8_-DKexWCCuNMsFdOQNMCs5XFjw', 'X-Restli-Protocol-Version' => '2.0.0'), 'json' => array('author' => 'urn:li:person:2aw2xskWL5', 'lifecycleState' => 'PUBLISHED', 'specificContent' => array('com.linkedin.ugc.ShareContent' => array('shareCommentary' => array('text' => 'L\'assistant marketing supervise la gestion des plannings et de l\'agenda de ses supérieurs, de l\'organisation de rencontres ou des déplacements. • Occasionnellement, il peut être amené à faire de la prospective par téléphone (phoning) ou par email (mailing). • Avec le chargé d\'études, il peut mener des analyses statistiques et assurer une veille des activités de la concurrence et en matière règlementaire.'), 'shareMediaCategory' => 'NONE')), 'visibility' => array('com.linkedin.ugc.MemberNetworkVisibility' => 'PUBLIC')), 'on_progress' => object(Closure))
But when I want to share a post it throws the following error :
HTTP/1.1 403 Forbidden returned for "https://api.linkedin.com/v2/ugcPosts".
The user in linkedin has admin right on the company page and the app has the following right : r_emailaddress, r_liteprofile, w_member_social
My guess is that OAuth 2.0 scopes needs to be changed but I cannot find out where to allow access to the functionality.
I found the origin of the problem.
While requesting the token, I did not grant « share » right to it.
Every thing works fine.

Google API - Oauth Refresh Token - Powershell

I'm writing a script that will download Google sheets using an Oauth access token. The script works just fine, but I'm having issues refreshing my access token.
Every guide I have found online shows me some iteration of the following:
$refreshTokenParams = #{
client_id=$clientId;
client_secret=$secret;
refresh_token=$refreshToken;
grant_type='refresh_token';
}
$refreshedToken = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body $refreshTokenParams
$accesstoken = $refreshedToken.access_token
When I run this script it returns the following:
StatusCode : 200
StatusDescription : OK
Content : <!doctype html><html lang="en" dir="ltr"><head><base href="https://accounts.google.com/"><script data-id="_gd" nonce="<Hidden just in case>">window.WIZ_global_data =
{"Mo6CHc":-<Hidden just in case>,"O...
RawContent : HTTP/1.1 200 OK
X-Frame-Options: DENY
Vary: Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site
google-accounts-embedded: 1
Pragma: no-cache
Transfer-Encoding: chunked
Strict-Transport-Security: max-...
Forms : {}
Headers : {[X-Frame-Options, DENY], [Vary, Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site], [google-accounts-embedded, 1], [Pragma, no-cache]...}
Images : {}
InputFields : {}
Links : {#{innerHTML=Learn more; innerText=Learn more; outerHTML=Learn more;
outerText=Learn more; tagName=A; href=https://developers.google.com/identity/protocols/oauth2; target=_blank; jsname=erTfTe}, #{innerHTML=Help; innerText=Help; outerHTML=<A
href="https://support.google.com/accounts?hl=en" target=_blank>Help</A>; outerText=Help; tagName=A; href=https://support.google.com/accounts?hl=en; target=_blank},
#{innerHTML=Privacy; innerText=Privacy; outerHTML=<A href="https://accounts.google.com/TOS?loc=US&hl=en&privacy=true" target=_blank>Privacy</A>; outerText=Privacy;
tagName=A; href=https://accounts.google.com/TOS?loc=US&hl=en&privacy=true; target=_blank}, #{innerHTML=Terms; innerText=Terms; outerHTML=<A
href="https://accounts.google.com/TOS?loc=US&hl=en" target=_blank>Terms</A>; outerText=Terms; tagName=A; href=https://accounts.google.com/TOS?loc=US&hl=en; target=_blank}}
ParsedHtml : System.__ComObject
RawContentLength : 1759969
When I save this output to an HTML file, I get this
Error 400: invalid_request
The error says "Required parameter is missing: response_type"
This Google doc mentions response_type='code' and I've added that to my array and that had no impact.
I feel like this section in the guide SHOULD work, but it doesnt. Unless maybe I'm implementing it wrong?
I have tried using "Invoke-restmethod" while specifying the content type to json/application, I've used alternative URIs and I've quadruple checked my client ID and password. I have no idea what I'm doing wrong.
If anyone has experience with refreshing Oauth access tokens using Powershell I would really appreciate your help.
Thanks in advance
I wrote this a while ago for gmail api GmailSendMail.psi
The issue is how you are sending the post body. It needs to be in the query parameters format.
function RefreshAccessToken([string]$clientId,[string]$secret, [string]$refreshToken){
$data = "client_id=$clientId&client_secret=$secret&refresh_token=$refreshToken&grant_type=refresh_token"
try {
$response = Invoke-RestMethod -Uri https://www.googleapis.com/oauth2/v4/token -Method POST -Body $data
return $response.access_token;
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
}
Let me know if you have any issues i will see if i cant update it for you.

How i can save a log with powershell in format pdf?

Actually i make one test unit that print this result:
info: serving app on http://127.0.0.1:4000
Usuario
superagent: Enable experimental feature http2
✓ realiza um registro de usuário (511ms)
✓ realiza login com o usuário registrado (142ms)
✓ realiza login com dados incorretos (145ms)
PASSED
total : 3
passed : 3
time : 2s
If i try to export this log in format .txt i have several problems with special characters and accents, as you can see:
adonis test > yourfile.txt
When i open the "yourfile.txt":
[32minfo[39m: serving app on http://127.0.0.1:4000
Usuario
Ô£ô realiza um registro de usu├írio (456ms)
Ô£ô realiza login com o usu├írio registrado (135ms)
Ô£ô realiza login com dados incorretos (126ms)
PASSED
total : 3
passed : 3
time : 1s
I'm thinking if there's a way to export this log in pdf to workaround this problem or if there's a way to show the special characters/accents correctly.
if i do a adonis test > yourfile.pdf the pdf generated is broken.
This may have to do with OutputEncoding.
Try:
$enc = [Console]::OutputEncoding
[Console]::OutputEncoding = [text.encoding]::utf8
adonis test | Out-File yourfile.txt -Encoding utf8 -Force
[Console]::OutputEncoding = $enc

Translating curl into Matlab/Webwrite

I have the following curl command I need to sent to a web server using Matlab and webwrite using POST. My problem is that I always get a "Bad request" answer so my syntax must be wrong somehow. Does anybody have an idea how this curl command, sending the body could look like in Matlab using webwrite in a correct way ?
body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"
I have just asked a potentially similar question so this may not work first time. However I cannot test without knowing some login details so I can but hope this helps.
data_InputValues = struct ('units',100,'instrument','EUR_USD','timeInForce','FOK','type','MARKET','positionFill','DEFAULT');
MyBody = matlab.net.http.MessageBody(struct('order',data_InputValues));
MyHTTPOptions = matlab.net.http.HTTPOptions(); % use this to change the options if necessary (e.g. extend timeout)
Request = matlab.net.http.RequestMessage;
Request.Method = 'POST';
Request.Header = matlab.net.http.HeaderField('Content-Type','application/json','Authorization: Bearer',AUTHENTICATION TOKEN);
Request.Body = MyBody;
uri = matlab.net.URI('https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders');
[response a ~] = Request.send(uri,MyHTTPOptions);
The part I struggle with is generating the MyBody part (in your case this is parsing the order variable's sub-variables). If you get this to work I would be keen to know how! P.S. my question in case it helps: Matlab RESTful PUT Command - net.http - nesting body values
The correct format for the body is as follows:
body = struct('units',100,'instrument','EUR_USD','timeInForce','FOK',...
'type','MARKET','positionFill','DEFAULT');
As for the HTTP headers that you require you can specify them with weboptions when using webwrite.
The syntax for an additional header:
options = weboptions('KeyName','Name','KeyValue','Value')
Where Name and Value are the name of the header and its value respectively.
You must add the headers that you require in weboptions.
For the code you provided, the correct syntax would be as follows:
options = weboptions('MediaType','application/json',...
'KeyName','Authorization: Bearer','KeyValue','Token');
You can then perform the POST request at the URL of interest.
response = webwrite(url,body,options);

Can't turn curl into Invoke-WebRequest

I've got a curl command that works great and I'm trying to turn it into a PowerShell Invoke-WebRequest call.
Here's the working curl with the multipart POST data:
curl -X POST "http://domain.com/admin/batchOrder/processBatch"
-F "ordersFile=#c:\temp\Sample_Auto_Order_Input_File.xml"
-F "psid=3002010250764"
-F "recipients[0]=astraljack#example.com"
And here's where I'm trying to do it via Invoke-WebRequest. Based on what I've read, I need to create a hash table of name-value pairs. I feel like I should be creating the hash table just like I do the multipart POST data above.
$form.clear()
$form.Add("ordersFile", "c:\temp\Sample_Auto_Order_Input_File.xml")
$form.Add("psid", "3002010250764")
$form.Add("recipients[0]", "astraljack#example.com")
$form
Then I can call Invoke-WebRequest.
Invoke-WebRequest http://domain.com/admin/batchOrder/processBatch -Body $form -Method Post
This fails with a 400 Bad Request. To be clear, I've never gotten this Invoke-WebRequest to work so I could be way off base here. I'm not even sure where I can look for a better error msg.
If it helps, the contents of the exception are
IsMutuallyAuthenticated : False
Cookies : {}
Headers : {Connection, Transfer-Encoding, Content-Type, Date...}
SupportsHeaders : True
ContentLength : -1
ContentEncoding :
ContentType : application/json;charset=UTF-8
CharacterSet : UTF-8
Server : Apache
LastModified : 5/12/2014 10:23:19 AM
StatusCode : BadRequest
StatusDescription : Bad Request
ProtocolVersion : 1.1
ResponseUri : http://domain.com/admin/batchOrder/processBatch
Method : POST
IsFromCache : False
The best way to solve the problem is to go download Fiddler and then capture the CURL request. Inspect its RAW request. Then do the same for the Invoke-WebRequest command. See what is different and that should tell you what you need to tweak with Invoke-WebRequest.
The #filepath syntax in curl actually reads the contents of the file into the parameter, but in your PowerShell version you are just setting the value of ordersFile to the filename. Try:
$form.clear()
$form.Add("ordersFile", (get-content "c:\temp\Sample_Auto_Order_Input_File.xml"))
$form.Add("psid", "3002010250764")
$form.Add("recipients[0]", "astraljack#example.com")
$form
Also, you may need to add -ContentType "application/x-www-form-urlencoded" to your Invoke-WebRequest call.
`
I know this is an old question, but I figured since it was still unanswered, I'd throw in my two cents. Here's how I would do this:
$form = #{
'ordersFile' = 'c:\temp\Sample_Auto_Order_Input_File.xml'
'psid' = '3002010250764'
'recipients[0]' = 'astraljack#example.com'
}
Invoke-WebRequest -Uri "http://domain.com/admin/batchOrder/processBatch" -Body $form -Method Post