RabbitMQ HTTP API returning 401 (Unauthorized) - rabbitmq

Using RabbitMQ localhost and trying to use his API.. when i Call from postman it's work fine.
But i'm trying to use this API inside my app code and I'm getting 401 error:
const test = {
count: 5,
ackmode: 'ack_requeue_true',
encoding: 'auto',
truncate: 50000
}
testPost() {
fetch('http://localhost:15672/api/queues/%2F/QA.MOBILE/get', {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(test),
headers: {Authorization: 'Basic ' + btoa('guest:guest'), Accept: 'application/json', 'Content-Type': 'application/json'}
});
}
POST http://localhost:15672/api/queues/%2F/QA.MOBILE/get net::ERR_ABORTED 401 (Unauthorized)
I'm missing something?
thanks

I just had this problem myself. Even though my issue was not CORS related, I thought I would document the issue here in case future readers have the same problem.
My issue was that I was not correctly base64ing the user credentials. From a browser you can just call any of the RabbitMQ API endpoints like this:
http://somename:somepassword#servername:15672/api/cluster-name
But when calling it programatically, you need to remove the credentials from the url and base 64 them instead.
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://servername:15672/api/cluster-name"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"somename:somepassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
string jsonContent = response.Content.ReadAsStringAsync().Result;
}
}
}
The above code is C# but it would be the same process for Java, etc.

Related

ERR_ABORTED 403 (Forbidden)

I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.
The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:
const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id = // API Key (deleted value for safety)
const secret = // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;
function GetAccessToken() {
var target_url = "https://api.sonos.com/login/v3/oauth/access/";
var authCode = GetAuthCode();
var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Authentication': `Basic {${encoded_msg}}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: "POST",
mode: "no-cors",
credentials: "include",
redirect: "follow",
headers: myHeaders,
body: params
}).then((res) => {
console.log(res.responseText);
}).catch(function(error) {
console.log(error);
});
}
function GetAuthCode() {
return (new URLSearchParams(location.search)).get('code'); // returns authorization code from URL
}
Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)
I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.
What could be the problem for this error message?
I noticed a couple of things in your code that may be causing your 403 Forbidden issue.
Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.
Addressing the above should hopefully resolve your issue!
Thanks,
-Mark

Ionic-native HTTP POST method not working on iOS (but perfectly working on Android)

I'm using #ionic-native/http in my Ionic 4 project for logging in user by sending body with UserId and Password and header with 'Content-Type': 'application/json' through POST method. Its working fine in android and but on iOS it responding with a http 400 error.
Dependencies:
"#ionic-native/http": "^5.3.0",
"cordova-plugin-advanced-http": "^2.0.9",
I tired using the #angular/http but its giving a CORS error on browser, android and iOS. And I can't change the server side code to enable CORS.
Code:
import { HTTP } from '#ionic-native/http/ngx';
// Login method
async login(userId, password) {
// login user
const httpBody = {
'UserId': userId,
'Password': btoa(password)
};
const httpHeader = {
'Content-Type': 'application/json',
};
const user = await this.http.post(this.loginURL, httpBody, httpHeader);
return JSON.parse(user.data);
}
Expected result response with StatusCode 200
Actual Result response with StatusCode 400
I waas having the same issue; in my case I fixed it by
setting the data serializer to 'utf8' and by setting the Content-Type header to 'application/x-www-form-urlencoded'
this.http.setDataSerializer('utf8');
const httpHeader = {
'Content-Type': 'application/application/x-www-form-urlencoded'
};

Aurelia HttpClient.Fetch to get token from Auth0 but works fine in Postman

I have no trouble getting a bearer token returned when using Postman. However, when using Aurelia, I receive a status 200 with "OK" as the only response. I see that the Request Method is still "OPTIONS". I see this in the Chrome Console:
Failed to load https://------.auth0.com/oauth/token: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
But, from what I can see the headers shown in the response and from what I'm seeing everything looks like it's there.
Here's what I receive from Postman:
Response: Status 200 OK
JSON:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGci...{shortened for brevity}",
"expires_in": 86400,
"token_type": "Bearer"
}
Here's code from Aurelia:
private getToken() {
var postData = { "client_id": API_CONFIG.clientId, "client_secret": API_CONFIG.clientSecret, "audience": API_CONFIG.audience, "grant_type": "client_credentials" };
this.http.fetch('https://kimberlite.auth0.com/oauth/token', {
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:3000/'
},
mode: 'cors',
method: 'post',
body: JSON.stringify(postData)
}).then(result => result.json())
.then(data => {
localStorage.setItem('api_access_token', data.access_token);
localStorage.setItem('api_expires_at', new Date().getTime() + data.expires_in);
});
}
I've searched and haven't found anything that's helped me get passed this. What am I missing? Any help greatly appreciated
After reading Jesse's comment below, I removed the header for the 'Access-Control-Allow-Origin' and receive the same 200 OK. However, receive error in Google Chrome Origin 'localhost:3000'; is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.".
After reading other questions, I attempted removing all headers and I receive a 401 Unathorized with the following response {{"error":"access_denied","error_description":"Unauthorized"}
private getToken() {
var postData = { "client_id": API_CONFIG.clientId, "client_secret": API_CONFIG.clientSecret, "audience": API_CONFIG.audience, "grant_type": "client_credentials" };
let http = new HttpClient();
http.fetch('https://kimberlite.auth0.com/oauth/token', {
credentials: 'omit',
//headers: {
// 'Content-Type': 'application/json'
//},
mode: 'cors',
method: 'post',
body: JSON.stringify(postData)
}).then(result => result.json())
.then(data => {
localStorage.setItem('api_access_token', data.access_token);
localStorage.setItem('api_expires_at', new Date().getTime() + data.expires_in);
});
}
ok, I just tried in Firefox, using only the 'Content-Type' header and received expected response. Is there something with Chrome (which most users are going to be using) that I need to be aware of?
You shouldn't set the access-control-allow-origin header on the request. In a CORS request, the server endpoint needs to set this header on the response of your OPTIONS request.
The way that Cross-Origin Resource Sharing works, is that the client first makes an OPTIONS call to the server endpoint. The server endpoint should be configured to use CORS, and have a list of origins that are allowed (or simply a * to allow all origins). Then on the response to this OPTIONS request, the server will set the Access-Control-Allow-Origin: https://localhost:3000 to indicate the origin is allowed to make the request. You can see this in your response too:
The client then proceeds to make the GET or POST call to the same endpoint and actually retrieve/store the data.
In your case, if you make the request using the Aurelia fetch client, you don't need to set a header to do this. You can simply do the following:
private getToken() {
var postData = { "client_id": API_CONFIG.clientId, "client_secret": API_CONFIG.clientSecret, "audience": API_CONFIG.audience, "grant_type": "client_credentials" };
this.http.fetch('https://kimberlite.auth0.com/oauth/token', {
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
mode: 'cors',
method: 'post',
body: JSON.stringify(postData)
}).then(result => result.json())
.then(data => {
localStorage.setItem('api_access_token', data.access_token);
localStorage.setItem('api_expires_at', new Date().getTime() + data.expires_in);
});
}

Angular 2 Post fail building request

I'm trying to do a simple post calling to my wcf rest service, and the result is a invalidoperation.
Using fiddler I see the request is not correct, but i don'w know why is not using my parameters.
I try JSON.stringify but don't work
private url = 'http://localhost:34244/CitizenService.svc/register';
public customLogin(user: string, pass: string): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ method: "POST",headers: headers,body: user} );
return this.http.post(this.url, user, options)
.map(this.extractData)
.catch(this.handleError);
}
And this is angular vs postman request
Anybody knows what's happening?
Thanks.

500 error on UrlFetchApp

I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.
However, 500 error occurred when fetching the REST resource from Googe Apps Script.
Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)
This is my Google Apps Script:
function myscript() {
var url = "http://mymagentohost/api/rest/products?limit=2"
var response = UrlFetchApp.fetch(url);
var out = JSON.parse(response.getContentText());
var doc = SpreadsheetApp.create("Product Info");
var cell = doc.getRange('a1');
var index = 0;
for (var i in out) {
var value = out[i];
cell.offset(index, 0).setValue(i);
cell.offset(index, 1).setValue(value);
index++;
}
Any ideas?
Hey the trick is to add the following headers to your request
var url = "http://mymagentohost/api/rest/products?limit=2"
var params = {
headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
muteHttpExceptions: true,
method: "GET",
contentType: "application/json",
validateHttpsCertificates: false,
};
var response = UrlFetchApp.fetch(url, params);
Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.