How to request url with authorized token through API - javascript

I am trying to develop a web-app based on girder platform (a data management platform). During development, I get some problem confused me for a long time. Let me briefly explain my work and if anything I understand worry, please point it out coz I just start.
The thing is that,
In the font end I am using AMI(a javascript library) to deal with image virtualization, and the way is to tell (make a request to girder server) AMI the URL address which contains image to display as attachment. (e.g.http://girderDomain:port/api/v1/file/imageID/download?contentDisposition=attachment API of girder)
When this URL does not have any permission, everything works fine. When it needs permission (which is a token generated when authorized user login), purely URL does not work, so I was trying to use ajax to make a request with requestHeader(token) something like below:
$.ajax({
type:'GET',
url:'http://girderDomain:port/api/v1/file/imageWithPermissionID/download?contentDisposition=attachment',
crossDomain:true,
processData: false,
beforeSend:function(xhr){
// xhr.setRequestHeader("Access-Control-Allow-Origin:", "*");
// xhr.setRequestHeader("girderToken", token);
},
success:function (d,s,xhr) {}
});
Although I still get some error not solving yet, but ajax is the only way that in my mind.
and the whole process is like pseudocode below:
//***AMI***//
var t2 = ["imageID",....]; //////No permission need image
files = t2.map(function(v) {
return 'http://girderDomain:port/api/v1/file/' + v+'/download?contentDisposition=attachment';
});
AMI.display(files)
As you can see no permission image display is simple and easy to do, and with permission image through ajax request would be something like:
//***ajax to download permission file first***//
$.ajax({
//url:'http://girderDomain:port/api/v1/file/imageWithPermissionID/download?contentDisposition=attachment'
//set requestHeader("girderToken",token);
//success:function(){
//download this permission file to request domain tempFolder as A
}
});
/***AMI***/
var t2 = ["A"];
files = t2.map(function(v) {
return 'http://requestDomain/tempFolder/A';
});
AMI.display(files);
and that looks stupid, so I am wondering does anyone have any idea to request a file with permission, like maybe save token in cookie or session and using some way to make request with cookie or session, or any other new methods, frameworks.
Since I just start that kind of client-server development, any help truly appreciated.

Related

Teams proactive messages and Graph API token

I'm trying to build a bot that sends proactive user recommendations regularly. They look similar to this one:
I have it all working in terms of user data coming from the backend, but I also want to add some additional things coming from the Graph API - one of which is the profile picture.
I've setup an Azure Bot Channel, got the Graph auth sample running, but I still can't figure how to mix the proactive messages with the OAuthPrompt dialog.
If I make the user sign in upon app registration, can I reliably get the graph token and use it in my proactive message handler? Note that these messages are going to be sent on a weekly basis. I'm afraid that the token is going to expire.
Has anyone done something similar?
If you just need the bot to make a call to Graph and retrieve user data, you can use Application Permissions to do this without having the user log in. First, you will need to enable the permissions in Azure Active Directory>App registrations>API permissions. The particular ones you need here is User.Read.All (or User.ReadWrite.All if you might want it to have write access for other use cases). There are also separate permissions for Group and Contact if you need that.
For the bot, you first need to get the token. There's a whole reference article here (which includes the app permissions as described above). The client ID and secret are the values for your application. So in javascript I do something like
var identityUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
var formData = `client_id=${clientId}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=${clientSecret}&grant_type=client_credentials`
try {
var idResponse = await request({
url: identityUrl,
method: 'POST',
headers: {'Content-Type': 'application/x-www-urlencoded;charset=UTF-8'},
form: formData
});
var token = JSON.parse(idResponse).access_token;
} catch (err) {
await step.context.sendActivity(`Sorry, something went wrong. Please try again later.`);
console.log(err.message);
return step.endDialog();
}
I've got a lot going on where I'm making an actual call to graph, but my http call looks like this:
var userResponse = await request({
url: usersUrl + queryString,
method: 'GET',
headers: {'Authorization':`Bearer ${token}`, 'ConsistencyLevel':'eventual'}
});
userResponse = JSON.parse(userResponse);
Now in your case you're calling the Get Photo endpoint, which I haven't done, but should be basically the same as the above. Here is a link for the Get photo documentation. So now, you bot should be able to authenticate and grab the picture before sending the proactive message, without any need for the user to ever give any credentials.

MarkLogic App Server Custom Login Page sessionID cookie with GET request

I am trying to develop a two-tier web application with MarkLogic-9 employing server side JavaScript and HTTP app servers. I have a simple page that prompts for username/password and sends a GET request via Ajax to the app server (application-level authentication).
My login.sjs script:
//generate object with field names from Request params
var params ={}; //JSON parsed URL parameters
var field_names = xdmp.getRequestFieldNames().toArray();
for(var fname_idx in field_names){
params[field_names[fname_idx]] = String(xdmp.quote(xdmp.getRequestField(String(field_names[fname_idx]))));
}
//get username and password from passed paramters
var username = params.username;
var password = params.password;
var ret = xdmp.login(username,password);
ret;
I have tested this and verified that it works by printing the xdmp.currentUser().
The login page then redirects to a home page that displays basic user info. My problem is that I cannot figure out how to preserve the current user's session after the client-side redirect to the homepage.
The app server has application-level authentication and a default user called Login-User, which is a custom user that has only the privileges necessary to log in (xdmp:login). The app server is hosted on localhost:8601. I have found that when I run login.sjs directly from the browser (i.e. typing localhost:8601/login.sjs?username=test_user&password=test_password), my browser gets a cookie with the sessionID. However, when I run the login.sjs via an Ajax GET request, my browser does not get any cookies. I don't know if this is the issue but I though it might be worth mentioning.
I am still a MarkLogic novice so I may be going about this the completely wrong way. Basically, how do I go about continuing a single user's session after redirecting to a new page? Do I use cookies to save the sessionID? Should I preserve the username and password in local storage and log in every time the website invokes a new .sjs file?
For completeness, here is the client side js I use to make the Ajax call to login. Pretty self-explanatory. The login.sjs file just returns true/false if the login was successful.
function createLoginEar(){
$("#login-button").click(function(event){
var un = $("#username").val();
var pw = $("#password").val();
if(un){
params.username = $("#username").val();
}
if(pw){
params.password = $("#password").val();
}
event.preventDefault(); //prevent form from clearing
console.log("input entered");
$.ajax({
type: "GET",
url: url,
data: params,
success: function(data){
if(data == "true"){
console.log("worked");
window.location.href = "homepage.html";
} else{
invalidLogin();
}
},
error: function(data){
invalidLogin();
}
})
})
}
The problem is that once the page redirects to homepage.html, there seems to be no memory of the user having logged in and when homepage.html calls any .sjs file, the user resets to the default which is "Login-User".
Thanks in advance.
I suggest you look at Chapter 15 of the security guide.
There is a sample of application level authentication using Custom Login Pages.
Lastly, the sample of IP-based login is not what you need, but shows you how to use xdmp.Login to switch users from the default application user.
I think that with all of that covered (not much to it really), you will be able to walk backthrough your setup and re-work it.
The issue was that my browser was not collecting cookies from the login because of issues that are over my head, but I found the answer in another post so this may be a duplicate.
Get and store cookie (from Set-Cookie) from an AJAX POST response.
I just had to include the following line in my ajax request:
xhrFields: { withCredentials: true },
Since this will throw an error if you have a wildcard in you Access-Control-Allow-Origin header, I also had to change this line:
xdmp.addResponseHeader('Access-Control-Allow-Origin', '*');
to this:
xdmp.addResponseHeader('Access-Control-Allow-Origin', 'http://localhost:8010');
And now my browser collects cookies.

Reconciling WP API, AngularJS, and $resource/$http requests (getting X-WP-TotalPages)

I'm putting together an app using WP-API with an Angular frontend. I'm developing locally, with the data I'm trying to use loaded in from a remote server. Doing a $resource request for all posts works great.
But, I'm trying now to get the result of the X-WP-TotalPages header and can't figure out how to do it. Here's the code as it stands:
var request = function() {
var fullRoute = 'http://dylangattey.com/wp-json/posts/';
var defaultGet = {
method: 'GET',
transformResponse: function(data, headers){
response = {};
response.posts = JSON.parse(data);
response.headers = headers();
console.log(headers['X-WP-TotalPages']);
return response;
}
};
return $resource(fullRoute, {}, {
get: defaultGet,
query: defaultGet
});
};
// This gives me back the first 10 posts
request().query();
Chrome and curl both show that X-WP-TotalPages should be equal to 2 as a header. However, it just logs undefined.
Am I missing something? No matter whether I use $http or $resource I get the same result. I also have the same issue whether I use a remote site or a local WP installation on localhost. Really, I just want to know the total number of pages or even just the total number of posts for a given request, so if there's a better way to do it, I'd love to know.
You probably need to control the access to the specific headers you want on the server side.
See this thread for a brief discussion, or MDN on Access-Control-Expose-Headers.

Cross-domain requests stopped working due to no `Access-Control-Allow-Origin` header present in the response

I have an error reporting beacon I created using Google Apps script and it is published to run as myself and to be accessible to "anyone, even anonymous," which should mean that X-domain requests to GAS are allowed.
However, my browsers are now indicating there is no Access-Control-Allow-Origin header on the response after the code posts to the beacon.
Am I missing something here? This used to work as recently as two months ago. So long as the GAS was published for public access, then it was setting the Access-Control-Allow-Origin header.
In Google Apps Script:
Code.gs
function doPost(data){
if(data){
//Do Something
}
return ContentService.createTextOutput("{status:'okay'}", ContentService.MimeType.JSON);
}
Client Side:
script.js
$.post(beacon_url, data, null, "json");
When making calls to a contentservice script I always have sent a callback for JSONP. Since GAS does not support CORS this is the only reliable way to ensure your app doesn't break when x-domain issues arrive.
Making a call in jQuery just add "&callback=?". It will figure everything else out.
var url = "https://script.google.com/macros/s/{YourProjectId}/exec?offset="+offset+"&baseDate="+baseDate+"&callback=?";
$.getJSON( url,function( returnValue ){...});
On the server side
function doGet(e){
var callback = e.parameter.callback;
//do stuff ...
return ContentService.createTextOutput(callback+'('+ JSON.stringify(returnValue)+')').setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I've lost a couple of hours with the same issue. The solution was trivial.
When you deploy the script as webapp, you get two URLs: the /dev one and the /exec one. You should use /exec one to make cross domain POST requests. The /dev one is always private: it requires to be authorized and doesn't set *Allow-Origin header.
PS.: The /exec one seems to be frozen — it doesn't reflect any changes of code until you manually deploy it with a new version string (dropdown list in deploy dialog). To debug the most recent version of the script with the /dev URL just install an alternative browser and disable it's web-security features (--disable-web-security in GoogleChrome).
Just to make it simpler for those who are only interested in a POST request like me:
function doPost(e){
//do stuff ...
var MyResponse = "It Works!";
return ContentService.createTextOutput(MyResponse).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I stumbled upon the same issue:
calling /exec-urls from the browser went fine when running a webpage on localhost
throws crossorigin-error when called from a https-domain
I was trying to avoid refactoring my POST JSON-clientcode into JSONP (I was skeptical, since things always worked before).
Possible Fix #1
Luckily, after I did one non-CORS request (fetch() in the browser from a https-domain, using mode: no-cors), the usual CORS-requests worked fine again.
last thoughts
A last explanation might be: every new appscript-deployment needs a bit of time/usage before its configuration actually settled down at server-level.
Following solution works for me
In Google Apps Script
function doPost(e) {
return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}
In JavaScript
fetch(URL, {
redirect: "follow",
method: "POST",
body: JSON.stringify(DATA),
headers: {
"Content-Type": "text/plain;charset=utf-8",
},
})
Notice the attribute redirect: "follow" which is very very important. Without that, it doesn't work for me.
I faced a similar issue of CORS policy error when I tried to integrate the app script application with another Vue application.
Please be careful with the following configurations:
Project version should be NEW for every deployment.
Execute the app as me in case you want to give access to all.
Who has access to the app to anyone, anonymous.
Hope this works for you.
in your calling application, just set the content-type to text/plain, and you will be able to parse the returned JSON from GAS as a valid json object.
Here is my JSON object in my google script doPost function
var result = {
status: 200,
error: 'None',
rowID: rowID
};
ws.appendRow(rowContents);
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
and here I am calling my app script API from node js
const requestOptions = {
method: 'POST',
headers: {'Content-Type': 'text/plain'},
body: JSON.stringify({param1: value, param2:value})
};
const response = await fetch(server_URL, requestOptions);
const data = await response.json();
console.log(data);
console.log(data.status);
My case is different, I'm facing the CORS error in a very weird way.
My code works normally and no CORS errors, only until I added a constant:
const MY_CONST = "...";
It seems that Google Apps Script (GAS) won't allow 'const' keyword, GAS is based on ES3 or before ES5 or that kind of thing. The error on 'const' redirect to an error page URL with no CORS.
Reference:
https://stackoverflow.com/a/54413892/5581893
In case this helps all any of those people like me:
I have a .js file which contains all my utility functions, including ones which call a GAS. I keep forgetting to clear my cache when I go to test updates, so I'll often get this kind of error because the cached code is using the /dev link instead of the /exec one.

HTTP Basic Authorization on IP Camera using AJAX / jQuery

I understand that this question was asked plenty of times before but it seems that none of the responses worked for me so here's my issue:
I have a Sony IP camera that is in the intranet. I am building a site with PHP/MySQL authentication for internal users to be able to view the MJPEG stream but the camera itself requires http authentication. I do not want to have the users enter their username and password to log into the camera page and then have to type the http authentication credentials (in the popup) to see the stream. I tried using jQUERY to change the headers to no avail. Keep in mind that the camera MUST have its own authentication so that users cannot just randomly type the IP and see the stream. I want to be able to control who views what and when.
I am assuming that if I make a correct authentication call when the user logs into the page, that camera will be available to them since they would have "silently" logged in. Also, if I use wget from the terminal with the --headers: "Authorization: blah_Blah" it actually works but I can't do this from jQuery! Here's my code:
$.ajax({
url : "http://some_ip_internally_for_the_cam/some_page_on_cam_that_needs_authentication_to_access_otherwise",
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', "some_base_64_stuff_that_works_in_wget");
},
success: function() {
$("div.log").attr("innerHTML", "ok");
}
});
This gets loaded as soon as the user logs in.
Any suggestions?
I had the same Javascript error in Firefox:
... 0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader] ...
As I was trying to set a new HTTP header in some XMLHttpRequest object:
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
The error occured because I was trying to set the HTTP header before the XMLHttpRequest.open() method.
Source:
http://www.webmasterworld.com/forum91/4542.htm
If you mean that div.log doesn’t display the “ok” message, it’s probably because your DOM code is incorrect. This:
$("div.log").attr("innerHTML", "ok");
sets a DOM attribute of the div, not its actual innerHTML. Instead, you should do:
$("div.log").html("ok");
Have you tried the username and password fields in .ajax?
$.ajax({
url: "http://mydomain/mypage.php",
username: "myUsername",
password: "myPassword",
error: function () {
}
}).done(function(html) {
//Do Stuff
});
This works for me in a similar scenario.

Categories