Authenticate Javascript Program for Gcloud AutoML Vision API - javascript

I am currently working on a project whereby I have used gcloud automl to train an image classifier. I have got it working fine and it is able to handle my requests using access-tokens. However, my issue lies in that access-tokens only last for an hour. I would like to be able to create a method in my client-side javascript or another way to authenticate such that it is indefinite and I do not need to manually generate new tokens.
I have looked through the samples and docs on gcloud and found a sample that describes a possibility with the People API but I am not sure how to translate this to the Vision API.
Currently I am sending a request like the following:
$.ajax({
url: "https://automl.googleapis.com/v1beta1/projects/(project-id)/locations/us-central1/models/(model-id):predict",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + "access-token");
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: objString,
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
If there is a way to alter this method (or write a new one) to make a permanent token or another authentication form that is indefinite, then that would be much appreciated.

You should use an environment variable along with a service account. Depending on your OS, you could use it until you turn off your machine, or set it as a permanent environment variable.

Related

Retrieve value from open external API - visual studio - javascript - AJAX

I would really appreciate some advice, I'm trying to retrieve information from an open API for the first time.
The API details are here,
https://data.police.uk/docs/method/neighbourhood-locate/
I want to retrieve the 'force' and 'neighbourhood' values and save them into variables, I want to save them as variables as I'm then calling googlemaps to display the KML map. I managed to get quite far on other sections of my code, such as geocoding a user inputted address and retrieving the Long/Lat, but I am now struggling to send the long/lat to the external API and save the response.
I've hardcoded the long/lat into the below URL for this advice request, I think I'm getting a response from the API but failing to capture the values into my variables. The debugger shows the following response, {"force":"metropolitan","neighbourhood":"00BK17N"}, below is my code,
var ForceId; //returned from the API
var Neighbourhood; //returned from the API
accessURL = "https://data.police.uk/api/locate-neighbourhood?q=51.500617,-0.124629"
//Use the zip code and return all market ids in area.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'jsonp',
success: function (data) {
ForceId.push(val.force);
Neighbourhood.push(val.Neighbourhood)
console.log(ForceId);
console.log(Neighbourhood);
}})
I made a few mistakes, after seeing the responses were coming back as errors for its syntax, I adjusted some settings, I removed contenttype as 'application/JSON' and the response could be seen in the consolelog to contain the needed parameters. I'm not sure of the implications of doing this or if its bad practice as I'm extremely new at this, its my first attempt at working with API's. So other may advise better.
function GetPolice(){
$.ajax({
type: "GET",
// contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'json',
success: function(data) {
ForceId = data.force;
Neighbourhood = data.neighbourhood;
},
})
}
If your new at this, then my suggestion is to tinker with 'success, error, complete' to see what responses are being returned to consolelog. Have a look at what your 'datatype' should be from the external API. Again, i'm not best placed to give advice but hope other new people find this helpful.
I now need to make the above a callback response, as it completes the function before the responsehas been recieved, I wish to use the response in another fucntion elsewhere, but thats a different challenge :)

Parse web application credentials and sending push to different credentials

I'm creating a web application and use Parse to manage users, I use my Parse applicationID and JavaScriptId.
Parse.initialize("my-app-id", "my-js-id");
Parse.User.logIn(username, password,...
When the user login to the site, he/she enter their Parse app-id and js-Id that belong to their mobile app that they want to push a notification to. And the website send notification to them:
Parse.initialize("their-android-app-id", "their-android-js-id");
Parse.Push.send({ where: new Parse.Query(Parse.Installation), data: ...
I'm not clear when to call initialize and how I distinguish between my javascript app and the android/iOS app that I want to send to.
As long as i know it isn't possible to use the same api with two diffrent api-keys. I think it would be the most easiest way to use the normal JavaScript-API for application A, but the REST-API for application B, since you only need to send push notifications for the application B.
In JQuery this could look for example like this:
$.ajax({
url: 'https://api.parse.com/1/push',
type: 'post',
data: {
where : {
...
},
data : {
...
}
},
headers: {
"X-Parse-Application-Id": "their-app-id",
"X-Parse-REST-API-Key": "their-rest-api-key",
},
contentType: 'application/json',
dataType: 'json',
success: function (data) {
//data: response data from the Parse.com REST-API
}
});
A quide from Parse about how to use push notifications through the REST-API is available here.

Creating an API in yii for cross domain communication

I am planning to create a Restful API in yii for cross domain communication. As what I have researched, cross domain communication can only be done via jsonp and my implementation is as follows:
UsersController:: actionCrossDomain
public function actionCrossDomain(){
$this->layout=false;
$data['data']['User']['name']= 'Johny';
$this->_sendResponse(200, CJSON::encode($data),'application/json');
}
UsersController::_sendResponse methdod it is the same as you can see in :Click here
On another server that i configured using virtual host, I am invoking the above method via ajax:
$( document ).ready(function() {
$.ajax({
type: "POST",
dataType: "jsonp",
url:'http:'http//uxaserver.local/alpha2/app/users/crossDomain' ,
data: null,
processData: false,
crossDomain: true,
contentType: "application/json",
success: function (data) {
console.log("done");
},
error: function (request, status, error) {
console.log(request);
}
});
});
The issue is my firebug is is complaining that : SyntaxError: invalid label
My requirement is such because I am helping my client's to do some customized analytic to his other websites and I need to put a script in his web pages of different domains so that the analytic data is recorded in the main server. I understand that I need to use the rest interface to communicate thus I am taking this approach. I am not sure if I have taken the right approach and please advice. I want to make it in a way where a client has an api key and can communicate with the api provided by me.
Is there any other approach to do this? Rather than jsonp?
As i see this string contents error
url:'http:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,
Should be
url:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,

Consuming web service in HTML

I have created a web service and saved its .wsdl file. I want to consume this service in my HTML file by providing its URL.
Can anybody tell me how to call the URL in HTML and use it?
Like its done here.
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr/
The only difference is my web service does not have an extention like "asmx?wsdl".
Does that makes any difference.
I followed that tutorial too but it does not produce any output.
Thank You////
You definitly should get familiar with AJAX.
You could use the ajax functionalities provided by jQuery. That's the easiest way, I assume. Take a look at http://api.jquery.com/jQuery.ajax/
You can use this like
$.ajax({
url: "urltoyourservice.xml"
dataType: "xml",
}).done(function(data) {
console.log(data);
});
HTML itself cannot consume a webservice. Javascript ist definitely needed.
The existence of your WSDL File looks like you are probably using a XML format as the return of the web service. You have to deal with XML in javascript. Therefore take a look at Tim Downs explanation.
But keep in mind, that your web service URL must be available under the same domain as your consumption HTML-File. Otherwise you'll receive a cross-site-scripting error.
yes you can use ajax but keep in mind you wont be able to make a request across domains. Consuming web services should be done in server side.
To further gain more knowledge about this, read How do I call a web service from javascript
function submit_form(){
var username=$("#username").val();
var password=$("#password").val();
var data = { loginName: username, password:password };
$.ajax( {
type: "POST",
url:"Paste ur service address here",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
var value = data.d;
if(value.UserID != 0){
alert.html('success');
}
},
error: function (e) {
}
});
}
Try this it will help

Authentication and Authorization for Web API with a Javascript plugin as a client

I am writing a Web Api (using asp.net Web Api) and naturally want clients to authenticate to use the service.
I was hoping to write a Javascript plugin that would make use of the Api and then make it available to be simply dropped into other web sites.
Is there a secure way I can have the plugin authenticate?
I'm not sure how I could keep any information passed to the plugin confidential.
I also want the API to be used by native apps, so does that rule anything making use of cookies?
Thanks
Is there a secure way I can have the plugin authenticate?
You are going to have to either embed the username/password in your plugin OR have some fields to get that information from the user.
Consider some code if you choose to embed the username/password:
$.ajax({
url: 'api/foo',
type: 'GET',
dataType: 'json',
success: onSuccess,
error: onError,
beforeSend: setHeader
});
note the assignment of beforeSend to setHeader:
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Basic YXBpX3VzZXIxOjEyMzQxMjM0');
}
Note, you will have to pre-calculate the auth string using the method below
Now if you want to pull the username/password from the user you could do this:
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', make_base_auth($("#username").val(), $("#password").val()));
}
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}

Categories

Resources