I'm trying to access API using Powershell Invoke-WebRequest, response of it is always "Authorization has been denied for this request" . however i fetched Access_token and punched into Postman and it works fine ,I am getting 200 response . So trying to figure out where i am going wrong within powershell.
My code Below
$loginInfo = #{
Username = $configData.UN
Password = $configData.PS
}
$loginInfo = $loginInfo | convertTo-Json -Depth 12
$authResult = Invoke-RestMethod $url -Method POST -ContentType "application/json" -Body $loginInfo
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", 'Bearer '+ $authResult.access_token)
Invoke-WebRequest -Method Get -Uri $url -Headers $headers
I figured it out, for some reason URL is case sensitive, i changed one of the URI segment from Uppercase to Lowercase and it started working. Strange but yes issue is fixed.
Related
I am trying to upload a file to OneDrive using the following code:
$graph_url = 'https://graph.microsoft.com/v1.0/me/drive/root:/filename:/createUploadSession';
$file = file_get_contents('logo.jpeg');
$headers = [
'Content-Type: json',
"Cache-Control: no-cache",
"Pragma: no-cache",
"Authorization: bearer EwAQA61DBAAUcSSzoTJJsy+XrnQXgAKO5cj4yc8AAewWnvfTuLAC2gDmYesGiVawqeIpfS8lJjyCyeXQMrKOu92FA0SK12N/87GBTs4ba2LJ5buqmm9gX18by0jPWzZ5qvpc+BdfMC2wUyiMYxh8QH8BJFBctAVgSaKM1KmhA8mAwb2czyw4OeWdupKH7qSPvjRtwBTTxxX8iIO3IeNbpXDghri9MWRGyVIffGf2Oi+RzQm5jbGuDtXrQa4K80m1o8PHcEkdIEXbaAgIE8oBYCVBQ7fyYxA84b0NjghSRbCZDj5rVbo1MDeBv0J4inmPthEbAMcS3fRSBdFs3+SSz+jZwb3SgSp5Q+VXiRs+keDQHspaoSNt4Ho0+pX94WQDZgAACAk/KNYU0yEY4AHihrs84QKvmWWfIOTYCBudQZD7tKp2ZeOpXEI7q3tOTuwHTv7uUmYxkpGswiNSeW2r9DEBdQ5gBtZ/YCXMPhlBLSxxahrl816zsj/UDi2c6dmB+6J1wk60/hm1Ll6vqn8YbtlyQh9hFLpWejo8+Vofh5/kRUfUSl1v7FIP7YIJLvTyNn1gGy9IMnxYdvba9ACGotVpFTAMNdjz6aQwUk4MJjD7csqYVpyMBh8O7bS40dRMjiUkdhXYvA03L/JV818qgo0W0uwJmoqzPJfe7VB+VekqxPCyVT6A86y/OaD1EsTaLwBILG8eS48Odr/qg7azjUsrdryS+rg7wfQEBEL+kIkS5Ne8eTg1/t2aAXFsUukiIBkTYp+Sold4yhqJU2w/cRDZiz9m3GBltjTS+JiIX2Ll0ABbOwmY9pkc6O8/3T0ZhgVuIigfIILTdMGMu9sNvJtVxYL4gbRlNX+gyMBHZHDo2zktdD5l4vDa+TTgn2Fc3CDUli/qLU1UX2SfJ6+B+epmX/wA32cXVtfDPcm605c18LipDoOVGxzf9RVyNe9e3VCFvR9UBmkobodVfE1VhUfzw/s5CHrjzCZ7ZZDt84Hm6VoWIVZLtYueHCuAaEhLa0gWZTKUSwvu3hCDwZUaAg==",
"Content-Length: ".filesize('logo.jpeg'),
];
$ch = curl_init($graph_url);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
$server_output = curl_exec($ch);
$info = curl_getinfo($ch);
The result, however, is the always the following error:
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: 8004920A",
"innerError": {
"request-id": "bab6035c-17c5-45ea-99ac-7c809e446ca2",
"date": "2018-12-22T09:42:03"
}
}
First of all, it seems like your token is incorrect. So step 1 is verify the token is correct. You can do that by copying your token and pasting it on the website Microsoft created specifically for this job. https://jwt.ms
Secondly as the microsoft documentation describes you have 2 ways of uploading a file to onedrive.
Direct upload (only for small files) docs
Through a upload session, docs
You're trying to do a direct upload to the CreateUploadSession endpoint.
The first way works (for small files) by uploading the file to the /content endpoint, but that is just a file only upload. So no content headers with json in them.
The second way works by creating an upload sessions (that responds with some json) and then do a second request for uploading the file to the endpoint you got from the url.
The documentation on these things are quite clear, and I think you're using PHP, so it should be easy to mimic the provided curl requests with php.
I am trying to use the grafana api (doc here http://docs.grafana.org/http_api/alerting/) to get the list of all the alerts in grafana.
Here's what I tried:
uri = URI("http://example:3000")
headers = {
'Authorization'=>'Bearer test',
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
http = Net::HTTP.new(uri.host, uri.port)
request1 = Net::HTTP::Get.new("/api/dashboards/uid/uKH1CKVmk")
response1 = JSON.parse(http.request(request1).body)
This one works, it returns the json of the dashboard, but when I try :
request2 = Net::HTTP::Get.new("/api/alerts?state=ALL") or
request2 = Net::HTTP::Get.new("/api/alerts?dashboardId="+response1["id"].to_s+"")
request2['Authorization'] = "Bearer test"
request2['Content-Type'] = "application/json"
request2['Accept'] = "application/json"
I get an empty json.
Any ideas what I am doing wrong ?
Thanks,
Nicu
Found the problem, when I created the API token I selected "Viewer" permissions, I was thinking its enough to just make a get request on alerts, but apparently it is not, made a new API token with "Admin" permissions and it works.
I am simply trying to get an access token from client id, client secret and tenant ID. Following powershell command works successfully
Invoke-RestMethod -Uri https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0 -Method Post -Body #{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "CLIENTID"; "client_secret" = "SECRET" }
But this curl doesn't work
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET" "https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0"
Neither this ruby script
require 'json'
require 'typhoeus'
url = 'https://login.microsoftonline.com/TENANT/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=CLIENTID&client_secret=SECRET"
HEADERS = {
"Content-Type" => "application/x-www-form-urlencoded"
}
resp = Typhoeus::Request.post(url, body: params, headers: HEADERS)
I am following this link. Any clues why neither of curl / ruby works ?
Thanks in advance
I tried to reproduce your issue successfully, and I discovered that the issue was caused by curl without OpenSSL and Typhoeus request without setting ssl_verifypeer: false.
So please follow this to check via curl --version and install openssl libraries on your environment.
Here is my sample code.
require "typhoeus"
url = 'https://login.microsoftonline.com/<tanet-id>/oauth2/token?api-version=1.0'
params = "grant_type=client_credentials&resource=https://management.core.windows.net/&client_id=<client-id>&client_secret=<client-key>"
headers = {
"Content-Type" => "application/x-www-form-urlencoded"
}
request = Typhoeus.post(url, body: params, headers: headers, ssl_verifypeer: false)
puts request.code, request.body
Hope it helps.
I'm trying to pipe support emails from my production mail server (Plesk 12 and Postfix) to send them to another VPS hosting my helpdesk installation, I have chosen ostickets helpdesk for many reasons (Open source,PHP/MySQL...)
So, the idea is to trigger email reception on some adresses such as contact#company.com, support#company.com... then resend them to ostickets via its API in order to create a new ticket there.
I tried this way
http://blog.absolutedisaster.co.uk/osticket-plesk-9-postfix-pipe-mail-to-a-progr/
It explains how to create a pipe to trigger email, lunch php script ...etc
Because of some permission issues, I kept all this configuration and change just the last thing : php script
So I've replaced this php script by a simple bash script doing the same thing : send a request to API to create a new ticket via CURL.
Now In my production mail server the pipe is recognized and the email is trigged successfully :
The same in the other side, osticket API is receiving the request:
The problem is that the http response is 400 as you can see, which means ans error code #66 in ostickets (malformed email).
So, I think the problem is in my bash script :
exec curl --header 'X-API-Key: API_KEY_HERE' --user-agent 'osTicket API Client v1.7' --data - 'http://support.company.com/api/tickets.email'
the original PHP script I have replaced by this is :
#!/usr/bin/php -q
<?php
# Configuration: Enter the url and key. That is it.
# url => URL to api/tickets.email e.g http://yourdomain.com/support/api/tickets.email
# key => API's Key (see admin panel on how to generate a key)
#
$config = array(
'url'=>'http://support.company.com/api/tickets.email',
'key'=>'API_KEY_HERE'
);
#pre-checks
function_exists('file_get_contents') or die('upgrade php >=4.3');
function_exists('curl_version') or die('CURL support required');
#read stdin (piped email)
$data=file_get_contents('php://stdin') or die('Error reading stdin. No message');
#set timeout
set_time_limit(10);
#curl post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $config['url']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket API Client v1.7');
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:', 'X-API-Key: '.$config['key']));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
curl_close($ch);
//Use postfix exit codes...expected by MTA.
$code = 75;
if(preg_match('/HTTP\/.* ([0-9]+) .*/', $result, $status)) {
switch($status[1]) {
case 201: //Success
$code = 0;
break;
case 400:
$code = 66;
break;
case 401: /* permission denied */
case 403:
$code = 77;
break;
case 415:
case 416:
case 417:
case 501:
$code = 65;
break;
case 503:
$code = 69;
break;
case 500: //Server error.
default: //Temp (unknown) failure - retry
$code = 75;
}
}
exit($code);
?>
What is missing in my bash script ? (especially the stdin input)
thank you so much,
UPDATE
The problem was indeed in the bash script, here is the solution I came up with:
#!/bin/bash
data=`cat -`
exec curl --header 'X-API-Key: API_KEY_HERE' --user-agent 'osTicket API Client v1.7' --data "$data" 'http://support.company.com/api/tickets.email'
The problem was indeed in the bash script, here is the solution I came up with:
#!/bin/bash
data=`cat -`
exec curl --header 'X-API-Key: API_KEY_HERE' --user-agent 'osTicket API Client v1.7' --data "$data" 'http://support.company.com/api/tickets.email'
This Powershell Command :
Invoke-RestMethod -Uri $uri -Method POST
-ContentType 'application/x-www-form-urlencoded; charset=utf-8' -Body $body
Gives this error:
System.Web.Services.Protocols.SoapException: Server was unable to process request. --->
System.Exception: Failed to execute the powershell script with error: The operation has timed out.
Executed Script:
$SubScription = '84372afc-befd-47f0-92db-268539982d02';
$FeaturePackID = '1c17cf71-8438-45ee-a14a-59ebe4332c36';
$CustomerOU = 'OU=ss34(ss34),OU=Customers,DC=MANHATTAN,DC=local';
Add-PSSnapin microsoft.sharepoint.powershell;
if ($SubScription -eq '') {
$sub = New-SPSiteSubscription;
} else
Please help me to fix this issue. Any help is much Appreciated.