How to call Microsoft Graph REST API with groovy-wslite - rest

I am trying to call Microsoft Graph API on groovy script using Java libraries. However, even though partly success, I still have some serious issues using it within my current project, so I think about trying to call the the REST API using groovy-wslite.
This is my current code for getting access token:
def authorizeHost = "https://login.microsoftonline.com"
def authorizePath = "/${azureSetting.getTenantID()}/oauth2/v2.0/authorize?"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.JSON
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}
The response from the log:
AADSTS900144: The request body must contain the following parameter: 'client_id'.
How can I change the above code, so that Microsoft Graph REST API can recognize my sending content and send back the access token.
UPDATE: After trying around, I found out that the body os post method should be as below:
type "application/x-www-form-urlencoded"
urlenc client_id: azureSetting.getClientID(),
scope: "https://graph.microsoft.com/.default",
response_type: "code"

according to doc https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request your request should have Content-Type: application/x-www-form-urlencoded
you are trying to send json instead
here is your code but pointing to a test httpbin.org server and it could show what exactly you are sending to server
there is a minor change: ContentType.JSON -> ContentType.URLENC
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3', transitive=false)
import wslite.rest.*
//just for test
def azureSetting = [ getClientID:{-> "12345"} ]
def LOGGER = [info:{x-> println x}]
//redefined host and url
def authorizeHost = "HTTP://httpbin.org"
def authorizePath = "/post"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.URLENC // <-- THE ONLY CHANGE IN YOUR CODE
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}

Related

How can I check with the calling URL domain with interceptors.request

I am new in exploring axios.
I would like to append Authorization for specific url I am calling
with ininterceptors.request.
Is it possible to check with what url I am calling ?
Let's take a look of my code right now.
service.interceptors.request.use(
config => {
config.headers["Authorization"] = "bearer " + getTokenA(); <---- Do this only when the api is /ApiA/
config.headers["Authorization"] = "bearer " + getTokenB(); <---- Do this only when the api is /ApiB/
return config;
},
error => {
Promise.reject(error);
}
);

Groovy rest client without libraries

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL
400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r
The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

SOAP Request to Wemo switch from Pebble returns status 500

Been trying to write a pebble app for wemo switches, currently this is the code i'm using:
function WemoRequest(callback) {
if (SOAPData === false || SOAPData === undefined) {
console.log("Invalid SOAP data: " + JSON.stringify(SOAPData));
return;
}
var url = "http://192.168.1.230:49153/upnp/control/basicevent1";
try {
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader("SOAPAction", "urn:Belkin:service:basicevent:1#GetBinaryState");
request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status === 200 && callback) {
callback(request, SOAPData);
}else{console.log("Status: "+request.status + " State: "+request.readyState+" Callback: "+callback);}
};
var packet = '<?xml version="1.0" encoding="utf-8"?>'+
'<s:Envelope xmls:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
'<s:Body>'+
'<u:GetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"></u:GetBinaryState>'+
'</s:Body>'+
'</s:Envelope>';
request.send(packet);
} catch (error) {
console.log("Error in XMLHttpRequest: " + error);
}}
I currently get status 500 from OnReadyStateChange and have no idea what I'm doing wrong. If this isn't enough code, app code is available here:https://github.com/dmf444/Webble
So...I know this is from 4 years ago lol, but I found this during a google search and just found the answer, so I figured I would respond for that reason: I think your header just needs an extra set of quotes around "urn:Belkin:service:basicevent:1#SetBinaryState" so that the string specifying the soapaction literally starts and ends with quotes.
I'm working in Python (because that's what all the kids seem to be doing these days), but I too was getting the 500 error until I made a very subtle change (the single quote marks around my double quotes) and almost cried tears of joy when my light turned off:
"SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"'
So here's the working version of the code (in Python lol):
import http.client
#Variables (value=on/off, ipaddress=address of your wemo)
value = 0 #1=ON, 0=OFF
ipAddress = "192.168.0.108"
#Build the SOAP Envelope (data)
data = '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>' + str(value) + '</BinaryState></u:SetBinaryState></s:Body></s:Envelope>'
#Build the Header (headers)
headers = {"Content-type" : 'text/xml; charset="utf-8"', "SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"', "Content-Length": len(data)}
#Send request and check response data (resp_data)
conn = http.client.HTTPConnection(ipAddress, 49153)
conn.request("POST", "/upnp/control/basicevent1", data, headers)
response = conn.getresponse()
resp_data = response.read()
if response.status == 200:
conn.close()
print("SUCCESS!")
elif response.status == 403:
print("ERROR: 403 (FORBIDDEN)")
else:
print("ERROR: " + str(response.status))

Getting 500 error while creating vertex using Rest API

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you

Problems uploading jpg with OneDrive Rest Api

For this HTML5 phone App I have to use the OneDrive REST API.
I managed to upload the file, but the file up on the server is not in .jpg format and won't display in a jpg viewer. After logging in through the REST API and getting a token back, I used XMLHttpRequest to PUT the file. I've tried passing it up as an ArrayBuffer and as a base64 encoded string. In each case the file makes it there, but is not decoded properly. I figured I needed to tell the webserver how to decode the file with "request.setRequestHeader('Content-Type', 'image/jpg')" ,but I get back the following error message from the OneDrive server:
"error": {
"code": "request_body_invalid_media_type",
"message": "The Content-Type header 'text/plain' isn't supported."
}
this.uploadFile = function (token, fileUri,fileName, fileTools, success, fail) {
var me = app.log('||Microsoft.uploadFile||');
fileTools.readFileContent(fileUri, 'dataUrl', gotData, fileError);
function fileError(err) {
app.logError(me + '::fileError:::' + err);
}
function gotData(base64String) {
var request = new XMLHttpRequest;
app.log(me + '::token::' + token);
request.open("PUT", "https://apis.live.net/v5.0/me/skydrive/files/" + fileName + "?access_token=" + token, true);
request.setRequestHeader('Content-Type', 'text/plain');
//request.setRequestHeader('Content-Type', 'image/jpg');
//request.setRequestHeader('Content-Transfer-Encoding', 'base64;charset=utf-8');
request.onload = function (e) {
app.log(request.responseText);
success(e);
};
request.onerror = function (e) {
app.log(me + '::7::');
fail(e.error.message);
};
app.log(me + '::8::' + base64String.substr(0,100));
var b = new Base64Stuff();
var aBuffer = b.base64ToBuffer(b.removeBase64jpgHeader(base64String));
request.send(aBuffer);
//request.send(base64String);
}
}
try
request.setRequestHeader('Content-Type', '');