So i have this project to access my ip cam stream through a website, but my camera interface has a header basic authentication.
I tried to use user credentials in my url but it doesnt work :
http://username:password#192.168.my-ip/
Also my password contains "#" so i encoded them with %40 and tried %2540 (for the encoding of %) too, doesnt work either.
I saw that maybe a JS post request like this could do the trick but i don't know where to find the clientSecret :
var clientId = "MyApp";
var clientSecret = "MySecret";
// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
var authorizationBasic = window.btoa(clientId + ':' + clientSecret);
var request = new XMLHttpRequest();
request.open('POST', oAuth.AuthorizationServer, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("username=John&password=Smith&grant_type=password");
request.onreadystatechange = function () {
if (request.readyState === 4) {
alert(request.responseText);
}
};
Related
I've now spent some time trying to get the JavaScript below working in my API (c#).
I run perfectly in JavaScript, but I get access denied as a response in my c# code.
JS :
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
document.getElementById('KundeListing').innerHTML = this.responseText;
console.log(this.responseText);
}
});
xhr.open("GET", "https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
xhr.setRequestHeader("Authorization", "Bearer " + Token);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.withCredentials = false;
xhr.send();
But When trying usingRestSharp; I am getting errors
'You are not currently authorized to access this product'
public string Get(string Token)
{
var client = new RestSharp.RestClient("https://plus.dnb.com/v1/search/typeahead?searchTerm=Wal&countryISOAlpha2Code=US");
var request = new RestRequest(Method.GET)
{
UseDefaultCredentials = true
};
request.AddHeader("accept", "application/json");
request.AddHeader("authorization", "Bearer " + Token);
IRestResponse response = client.Execute(request);
return response.ToString();
}
I'm trying to make a PSOT request to the Microsoft Oauth2.0 token URL using NodeJS and the XMLHttpRequest library found here. However, I am having the problem, that I just can't send a proper Request body alongside with the Request. I have already tried using FormData from here, I tried URLSearchParams, and I tried making it a String in the way we know it from our Adress bar in GET Requests. Below you can see my Code from when I tried doing it in a GET URL form, and in the part that I made a commend, you can see my attempts of using FormData instead.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'https://login.microsoftonline.com/common/oauth2/v2.0/token');
/*var data = new FormData();
//var data = new URLSearchParams();
data.append('client_id', clientId);
data.append("grant_type", "authorization_code");
data.append("scope", "openid email profile");
data.append("code", code);
data.append("redirect_uri", "http://" + req.headers.host + req.url);
data.append("client_secret", secret);
Error message on this one: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of FormData
Same message with URLSearchParams, except it received an instance of URLSearchParams
*/
var data = 'client_id=' + clientId;
data += '&grant_type=authorization_code';
data += '&scope=openid%20email%20profile';
data += '&code=' + code;
data += '&redirect_uri=' + encodeURIComponent("http://" + req.headers.host + req.url);
data += '&client_secret=' + secret;
//This one gives me an error message from Microsoft: {"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: ratherNotSay\r\nCorrelation ID: ratherNotSay\r\nTimestamp: 2020-02-10 10:37:36Z","error_codes":[900144],"timestamp":"2020-02-10 10:37:36Z","trace_id":"ratherNotSay","correlation_id":"ratherNotSay","error_uri":"https://login.microsoftonline.com/error?code=900144"}
//This must mean that the request body can not have been submitted in the right way.
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log(xhr.status + "\n" + xhr.responseText + "\n");
}
};
xhr.send(data);
You can transform a URLSearchParams instance into a query string, like the one that you build manually, by using the toString() method.
I don't know if the Content-Type header is set to application/x-www-form-urlencoded by default in the node-XMLHTTPRequest version, but it couldn't hurt to set it manually.
const xhr = new XMLHttpRequest();
xhr.open("POST", 'https://login.microsoftonline.com/common/oauth2/v2.0/token');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
const data = new URLSearchParams();
data.append('client_id', clientId);
data.append("grant_type", "authorization_code");
data.append("scope", "openid email profile");
data.append("code", code);
data.append("redirect_uri", "http://" + req.headers.host + req.url);
data.append("client_secret", secret);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log(xhr.status + "\n" + xhr.responseText + "\n");
}
};
xhr.send(data.toString());
I am trying to get the locations list of a user with Google My Business Javascript API (https://developers.google.com/my-business/quickstarts/javascript). A user logs in successfully with his google credentials and oauth token is generated. But When I am trying to get the locations--->
var apiKey = 'xxxxxxxxxxxxxx';
var clientId = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var gmb_api_version = 'https://mybusiness.googleapis.com/v4';
let user = gapi.auth2.getAuthInstance().currentUser.get();
let oauthToken = user.getAuthResponse().access_token;
let xhr = new XMLHttpRequest();
let req = gmb_api_version + '/' + 'accounts/' + user.getId() + '/locations';
xhr.responseType = 'json';
xhr.open('GET', req);
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken);
xhr.send();
I am getting null in xhr.response object.
It is somehow late to answer but in case somebody needs:
If you do not have the error then probably, just the account has no locations. first check the google response in [https://developers.google.com/oauthplayground/], trying to see if you have the different response.
I am getting the raw data of the drafted from Gmail API "get" method and sending it using Gmail API "send" method.
'var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/id?
format=raw&alt=json&access_token=' + token;
url = url.replace("id", emailId);
var x = new XMLHttpRequest();
x.open('GET', url , true);
x.send();
x.onload = function() {
var jsonRes = JSON.parse(x.response);
sendEmail(jsonRes.raw);
}
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json&access_token=' + token;
params = "raw=" + raw;
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}`
I am getting 401 status.
If I am sending this raw data from API page itself, then it is sent successfully. Therefore the raw data is correct.
I am missing something while sending the email. Please help!
A 401 error means "invalid credentials", most likely because your token has expired or isn't valid.
The Google API explorer and Google Javascript libraries take care of the token for you (generally), but if you're calling the service endpoints directly with XMLHttpRequest(), you'll have to manage the token yourself.
If you want to go that route, here are the details you have to implement: https://developers.google.com/identity/protocols/OAuth2
You can try things out in the "Oauth2 playground": https://developers.google.com/oauthplayground/
Thank you for all responses.
I sent the email using the following code-
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send';
var params = JSON.stringify({'raw': raw});
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}
}
There were two mistakes I rectified-
1. The token was sent in URL as well as header. It should be sent only in header.
2. The param raw was sent as String but it should be sent as a JSON object.
I'm trying to create a plugin to check some values hosted on a local site. the auth on the page is done via Windows Authentication.
so I was trying to create an xhr request, but that still gave me 401
// method 1
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true, "User","Password");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
}
same for an ajax request (with the webtoolkit.base64.js)
// method 2
function make_basic_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function get_info2(url){
var auth = make_basic_auth('User','Password');
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
}
So is it just impossible to fetch that data in via an extention, or am I doing something wrong?