angularjs and googles url shortener - javascript

I have an issue at the moment with the google url shortener.
I have set up this service:
angular.module('widget.core').service('urlShortener', service);
function service($log, $q, $http) {
var gapiKey = '<MyApiKey>';
var gapiUrl = 'https://www.googleapis.com/urlshortener/v1/url';
return {
shorten: shorten
};
//////////////////////////////////////////////////
function shorten(url) {
console.log(url);
var data = {
method: 'POST',
url: gapiUrl + '?key=' + gapiKey,
headers: {
'Content-Type': 'application/json',
},
data: {
longUrl: url,
}
};
return $http(data).then(function (response) {
$log.debug(response);
return response.data;
}, function (response) {
$log.debug(response);
return response.data;
});
};
};
As far as I can tell, this should work. I have put in the correct API key and when I run this method I get this error:
{
error: {
code: 401,
message: 'Invalid credentials'
}
}
But, if I use postman and set it up exactly like this method:
Make it post
Add the content-type header and set it to application/json
set the url to https://www.googleapis.com/urlshortener/v1/url?key=myapikey
set the body to:
{
longUrl: 'myreallylogurl.com'
}
When I post this, it works with no issues.
I have checked my application on the google console and it is definitely set to unrestricted.
Has anyone come across this issue before? Does anyone know how to solve it?

I figured this out, it was nothing to do with the code above, but I thought I would answer my own question because someone else may run into the same issue.
In the project I have an httpInterceptor set up that adds the authetentication token to each request for talking to my API. This was what was causing the issue.
It so happened that I already defined a constant for my apiUrl, so I just updated the interceptor to check to make sure that the request url was my api before trying to append the token.
Like this:
angular.module('widget.core').factory('authInterceptor', factory);
function factory($q, $location, $localStorage, apiUrl) {
// The request function
var request = function (config) {
// If we are querying our API
if (config.url.indexOf(apiUrl) > -1) {
// Get our stored auth data
var authData = angular.fromJson($localStorage.get('authorizationData'));
// Set our headers to the request headers or a new object
config.headers = config.headers || {};
// If we have any auth data
if (authData && authData.authenticated) {
// Set our authorization header
config.headers.Authorization = 'Bearer ' + authData.token;
}
}
// Return our config
return config;
};
return {
request: request
};
};
I hope that helps someone else. Took me hours to figure it out :/

Related

Fetch googlesheet data using access token?

I want to fetch googlesheet data. Through my code I am able to get the access token but now I don't know how can I fetch all the records in a googlesheet using that particular access token in javascript.
I have given the scope in manifest as spreadsheet.readonly.
I have my token in a particular variable and also googlesheeetId in another variable now what headers and what url do I need to paas so that I can get the googlesheet data.
Please help with some reference or links or sample code so that I can get a glimpse of what process do I need to follow to do this.
Here is the code
var gSheetId;
chrome.identity.getAuthToken({ 'interactive': true }, function (token) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
return;
}
console.log(token);
//getting googlesheetId from user
gSheetId = prompt("Please provide your googlesheet Id");
if (!gSheetId) {
alert("Operation Cannot be Performed! Please refresh");
}
else {
//read googlesheetdata
var headers = {
'Authorization':'Bearer '+token
}
//here I need to read the googlesheet data using the token
chrome.debugger.onEvent.addListener(onEvent);
}
});
Thanks in advance!
Solution
Brought to you by #StayAtOrbit , owner of the oiginal question. (this is a community wiki answer)
Useful resources for this issue:
Google sheets API documentation for JavaScript
Sending access token to an API
Making authentificated requests with a token
var gSheetId;
chrome.identity.getAuthToken({ 'interactive': true }, function (token) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
return;
}
console.log(token);
//getting googlesheetId from user
gSheetId = prompt("Please provide your googlesheet Id");
if (!gSheetId) {
alert("Operation Cannot be Performed! Please refresh");
}
else { //read googlesheetdata
var obj = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Host': 'sheets.googleapis.com',
'Authorization': 'Bearer '+token
}
}
fetch('https://sheets.googleapis.com/v4/spreadsheets/<sheetID>/values/<range>', obj)
.then(function (res) {
return console.log(res.json());
}).then(function (resJson) {
return console.log(resJson);
})
//here I need to read the googlesheet data using the token
chrome.debugger.onEvent.addListener(onEvent);
}
});

How to use Auth0 JWT with angularjs for payLoad data

I am new to auth0 Here, I am getting an JWT-Token in the login request .
So, Lets say, "12344566" thie is the JWT-Token. now , I have now stored this in the localstorage .
jwtOptionsProvider.config({
tokenGetter: function() {
return localStorage.getItem("AuthToken");
},
});
$httpProvider.interceptors.push('jwtInterceptor');
I am using jwtInterceptor for sendig this token in every request . Now,
below is my request ->
addToOntology: function (ontologyName, currentNode, orphan, type) {
var config = {};
config.headers = {
"Content-Type": "application/json",
};
var jsonData = {
"ontologyName": ontologyName,
"orphanName": orphan,
"orphanType": type
};
return $http.put('abv/ontology/' + currentNode.name, jsonData, config)
.then(function (success) {
return success;
},
function (error) {
$log.error(error);
return $q.reject(error);
});
},
Now, If you see here this is my service which is calling a rest api . Here I am sending jsonData . Right now with this code Authorization Bearer 123456 This gets added in header but the jsonData is not getting converted in the jwt . So, How can I do this ? Thanks in advance.

AngularJS Adding a header to the $http.get

I'm trying to add the 'Authorization' header containing a token for future HTTP request. Retrieval of the token seems to be fine however when making a get request it fails with an Unauthorized error message. After checking the request headers Authorization header does not exist in the request block...
window.crUtil = /*window.crUtil ||*/ (function() {
// Angular Services
var $injector = angular.injector(['ng']);
var $http = $injector.get('$http');
// getting the CFF data
function get_data() {
getJWTAWS();
var url = '/AWS/getDATA/555';
console.log('AUTH header before call: ' + $http.defaults.headers.common.Authorization);
$http.get(url,httpHeader).then(function successCallback(response) {
var data = response.data;
var cff = initCff();
alert(data.itemId);
}, function errorCallback(response) {
initCff();
alert("Error while getting data ");
});
}
function getJWTAWS() {
var httpConfig = {
cache: true,
params: {}
};
$http.get('/AWS/token', httpConfig).then(
function(response) {
if (response.data.accessToken) {
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = response.data.tokenType + ' ' + response.data.accessToken;
}
},
function(error) {
alert('jwt token could not be retrieved.');
}
);
}
})();
var result = util.get_data();
console.log ('called search function ' + result);
Function getToken() returns a value but as I'm new on that topic I'm not quite sure if the way I added the token to the headers is proper.
Could you please advise on the proper way to include the headers in the request. I also tried to add it to the get request like
$http.get(URL,httpHeaders)...
but it also didn't work.
I'm not sure I understand your problem completely as you did not provide what you call
httpConfig
If you're struggling to declare the headers, try making the get request like this:
$http({
method: 'GET',
url: YOUR_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': AUTH_STRING_HERE
}
}).then(function (response) { ... });
You can add any headers you like in the headers object there.
Try adding this in your config block and set the token in your rootscope
$httpProvider.interceptors.push({
request: function (config) {
config.headers.Authorization = $rootScope.token;
return config;
}
})

401 unauthorized except through browser

I've been trying to do an HTML GET request, using a URL that works in the browser but somehow results in a 401 Unauthorized error when I run my code. The problem is that I did provide authentication; the URL is of the form
http://username:password#url?param=value
It succeeds in Firefox and Chrome (I also went through Incognito mode to avoid cookies), as well as Google's Postman app, but despite trying several other HTTP GET request methods they all return unauthorized error. I've run it through REST API and XMLHttpRequest, as well as command line.
Any ideas on what could be causing this? Or, even better, if someone's had a similar problem and has a solution?
(Note: I'm pretty new to this whole thing, not sure if I was clear/detailed enough. I'll do my best to elaborate if anyone needs.)
Edit: Here's some idea of the original code I was running:
var func = function() {
var options = {
baseUrl: SERVER,
uri: '/device.cgi',
qs: {
param1: value1,
param2: value2
}
};
request(options, function(err, response, body) {
if (err) console.log(err);
else console.log(body);
});
};
I also ran
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
from this question and got the same Unauthorized result.
And because apparently the device I'm using is fine with POST as well,
var func = function () {
var formData = {
form: {
param1: value1,
param2: value2
}
};
request.post(SERVER + 'device.cgi', formData, function (err, response, body) {
if (err) {
console.log(err);
}
else console.log(body);
}).auth(userID, userPass);
};
still with exactly the same result.
http://username:password#url?param=value
The browser is taking that URL, and creates the Basic HTTP Authorization header for you.
Node.js does not do that for you, and thus you must set the Authorization header yourself in code.
var http = require('http');
var options = {
host: 'www.tempuri.org',
path: '/helloworld/',
headers: {
'Authorization': 'Basic QWxhZGRpbjpPcGVuU2VzYW1l'
}
};
http.request(options, function(response) {
var body = '';
response.on('data',function(c) {
body+= c;
})
response.on('end',function() {
console.log(body)
})
}).end();
The following links discuss basic auth, how the browser encodes the data in the URL, and how you could implement it yourself in Node.js:
Basic access authentication (Wikipedia)
Can you pass user/pass for HTTP Basic Authentication in URL parameters? (serverfault)
Basic HTTP authentication in Node.js using the request module (Hay Kranen)

GET x-Auth-Token via JavaScript/Angular/Ionic Promise

I have a problem and don´t know how to solve it...
I have to authenticate a user in my IonicApp through a token based authentication. So i have to store the token inside the app, which shouldn´t be a problem...
The Problem is: How can i get the token?
Here´s my code:
// Alle Aufrufe an die REST-Api werden hier durchgeführt
var httpCall = {
async : function(method, url, header, params, data) {
// if (url != 'login') {
// header['X-Auth-Token'] = userTokenFactory.getUserToken();
// }
//console.log(header['X-Auth-Token']);
var ipurl = "IPURL";
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http({
method : method,
url : ipurl + url,
//headers : header,
params : params,
data : data,
config : {
timeout : 5000
}
}).then(function successCallback(response) {
//console.log("data:" + response.data);
//console.log("header:" + response.headers);
console.log("token:" + response.headers['X-AUTH-TOKEN']);
//console.log(response.data.token);
console.log("token" + repsonse.token);
// TRY TO READ THE X_AUTH_TOKEN HERE !!!!!!!!!!!!
return response;
}, function errorCallback(response) {
return response;
});
// Return the promise to the controller
return promise;
}
};
return httpCall;
});
And here´s a picture of the Response from the Server (from Firefox). As you can see, the X-Auth-Token is there...
here´s the x-auth-token
Thanks for the help!!
There are lot of articles are available over handling authentication in AngularJS. This article is the one perfect suitable in your case.
So you can get token from your request as,
}).then(function successCallback(response) {
console.log("data:" + response.data);
$window.sessionStorage.token = response.data.token;
return response;
}, function errorCallback(response) {
return response;
});
Now we have the token saved in sessionStorage. This token can be sent back with each request by at least three ways
1. Set header in each request:
`$http({method: 'GET', url: url, headers: {
'Authorization': 'Bearer ' + $window.sessionStorage.token}
});`
2. Setting defaults headers
`$http.defaults.headers.common['X-Auth-Token'] = 'Bearer ' + $window.sessionStorage.token;`
3. Write Interceptor:
Interceptors give ability to intercept requests before they are
handed to the server and responses before they are handed over to the
application code that initiated these requests
myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
}
return response || $q.when(response);
}
};
});
myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
Refer AngularJS $http guide for detailed explanation.
As you are getting response.data null and image demonstrates that headers are being returned, I would suggest you to check if you are getting data with
response.headers(),
if then try with response.headers()["X_AUTH_TOKEN"].

Categories