GET request from NetSuite to Oracle EPM, but faced with "Authorization Required - You are not authorized to access the requested resource - oracle

Error: "Authorization Required - You are not authorized to access the requested resource. Check the supplied credentials (e.g., username and password)."
Using the same exact headers and URL, I am successfully able to make the request get through via Postman and Powershell. But when doing the call via SuiteScript, I get the auth error. I am thinking it may have something to do with me constructing the headers.
Here is the code I used via NetSuite Debugger:
require(['N/https', 'N/encode'], function(https, encode) {
function fetchCSVdata() {
var authObj = encode.convert({
string : "username:password",
inputEncoding : encode.Encoding.UTF_8,
outputEncoding : encode.Encoding.BASE_64
});
var psswd = 'Basic ' + authObj;
var headerObj = {'Authorization' : psswd};
var response = https.get({
url: 'https://<bleep>.pbcs.us6.oraclecloud.com/interop/rest/11.1.2.3.600/applicationsnapshots/DemandPlan_ExportItemPlan.csv/contents',
headers: headerObj
});
return response.body;
};
var x = fetchCSVdata();
log.debug("error", x);
});

Looking at some working code of mine it is different than yours but I don't see the error.
var authstring = encode.convert({string: 'username:password',
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64});
var headerObj = {Authorization: 'Basic '+ authstring };
var response = https.get({url: 'https://webservices.XXX.com', headers: headerObj});

Related

Failed to retrieve clubhouse.io api using UrlFetchApp.fetch

Problem Statement: Unable to retrieve data using clubhouse.io api
in Google sheets > Script Editor
Per developers.google.com: Certain HTTP methods (for example, GET) do not accept a payload.
However, the clubhouse v3 api expect body/payload in GET request
Here is method:
function getClubhouseStories() {
try{
var myHeaders = {"Content-Type": "application/json"};
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: JSON.stringify({"query":"lable\:my label"}),
redirect: 'follow',
query: {"token": "XXXXXXXXUUIDXXXXX"},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch("https://api.clubhouse.io/api/v3/search/stories", requestOptions);
}
catch(error) {
console.error(error);
}
var responseCode = response.getResponseCode();
var responseContent = response.getContentText();
Logger.log(responseCode);
Logger.log(responseContent);
}
Returns:
responseCode >> 401
responseContent >> "{"message":"Sorry, the organization context for this request is missing. If you have any questions please contact us at support#clubhouse.io.","tag":"organization2_missing"}"
The same request works perfect via postman or bash, and requests that don't need body also work via UrlFetchApp.fetch
Tags:
#clubhouse-api #google-apps-scripts #postman
You can include the token and query parameters as part of the URL.
function getClubhouseStories() {
try {
var requestOptions = { muteHttpExceptions: true };
var parameters = {
token: 'XXXXXXXXUUIDXXXXX',
query: 'label:"my label"' // Clubhouse API requires using double quotes around multi-word labels
};
var url = "https://api.clubhouse.io/api/v3/search/stories";
var response = UrlFetchApp.fetch(buildUrl_(url, parameters), requestOptions);
} catch (error) {
console.error(error);
}
var responseCode = response.getResponseCode();
var responseContent = response.getContentText();
Logger.log(responseCode);
Logger.log(responseContent);
}
/**
* Builds a complete URL from a base URL and a map of URL parameters.
* Source: https://github.com/gsuitedevs/apps-script-oauth2/blob/master/src/Utilities.js#L27
* #param {string} url The base URL.
* #param {Object.<string, string>} params The URL parameters and values.
* #return {string} The complete URL.
* #private
*/
function buildUrl_(url, params) {
var paramString = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
return url + (url.indexOf('?') >= 0 ? '&' : '?') + paramString;
}
Other issues you're facing are related to request options that aren't valid UrlFetchApp parameters:
Default method is 'GET', so no need to specify
Content-Type should be specified using contentType, but it defaults to "application/x-www-form-urlencoded", so no need to specify
body is not valid. Should use payload instead, but not in this case, because we need to include parameters in the URL.
redirect is not valid. Should use followRedirects, but that already defaults to true.
query is not valid. Need to manually include in the URL.
The message you received, Sorry, the organization context for this request is missing. is the error you'll receive when you fail to send an authorization token/header.
You need something like this:
var myHeaders = {"Content-Type": "application/json", "Shortcut-Token": "<token>"};
Shortcut API docs

spotify application requests authorization

I am trying to get 'access token' from spotify with the following code.
var encoded = btoa(client_id+':'+client_secret);
function myOnClick() {
console.log('clikced!');
$.ajax({
url: 'https://accounts.spotify.com/api/token',
type: 'POST',
data: {
grant_type : "client_credentials",
'Content-Type' : 'application/x-www-form-urlencoded'
},
headers: {
Authorization: 'Basic ' + encoded
},
dataType: 'json'
}).always((data)=> console.log(data));
}
however I keep getting errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://accounts.spotify.com/api/token.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
and
readyState: 0, status: 0
Arielle from Spotify here.
Looks like you're using the Client Credentials Flow, which is one of 3 Authentication flows you can use with the Spotify API. (You can check out all 3 here)
Client Credentials is meant for server-side use only, and should not be used on the front-end, as it requires a client secret which you shouldn't be exposing!
You should use the Implicit Grant flow, which is made for use in the browser, instead. It's easy to get up and running, too!
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
'user-read-birthdate',
'user-read-email',
'user-read-private'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}
Gist: https://gist.github.com/arirawr/f08a1e17db3a1f65ada2c17592757049
And here's an example on Glitch, that you can "Remix" to make a copy and start making your app: https://glitch.com/edit/#!/spotify-implicit-grant
Hope that helps - happy hacking! 👩🏼‍💻
const result = await axios({
url: this.apiLoginUrl,
method: 'post',
data: "grant_type=client_credentials",
headers: {
'Authorization': `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString('base64')}`,
},
});

Asynchronous form-data POST request with xmlhhtprequest

I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);

Difficulty creating a functional Angular2 post

I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.

How to make dojo.request.xhr GET request with basic authentication

I look at the documentation for Dojo v.1.9 request/xhr
and I cannot find example that includes basic authentication.
How and where do I include the User name and Password in the Dojo XHR options?
require(["dojo/request/xhr"], function(xhr){
xhr("example.json", {
// Include User and Password options here ?
user: "userLogin"
password: "userPassword"
handleAs: "json"
}).then(function(data){
// Do something with the handled data
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
});
Thanks.
Indeed, you should be able to pass the user and password with the user and password property in the options object.
In previous versions of Dojo this was documented, but it seems that now they aren't. However, I just tested it and it seems to add the username and password to the URL, like:
http://user:password#myUrl/example.json
Normally the browser should be capable of translating this URL so the request headers are set.
You could also set these headers manually, for example by using:
xhr("example.json", {
headers: {
"Authorization": "Basic " + base64.encode(toByteArray(user + ":" + pass))
}
}).then(function(data) {
// Do something
});
However, this requires the dojox/encoding/base64 module and the following function:
var toByteArray = function(str) {
var bytes = [];
for (var i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
};

Resources