How can I check with the calling URL domain with interceptors.request - axios

I am new in exploring axios.
I would like to append Authorization for specific url I am calling
with ininterceptors.request.
Is it possible to check with what url I am calling ?
Let's take a look of my code right now.
service.interceptors.request.use(
config => {
config.headers["Authorization"] = "bearer " + getTokenA(); <---- Do this only when the api is /ApiA/
config.headers["Authorization"] = "bearer " + getTokenB(); <---- Do this only when the api is /ApiB/
return config;
},
error => {
Promise.reject(error);
}
);

Related

Google Storage REST get with axios

I want to get a list of images in a bucket using REST and axios.
ref: https://cloud.google.com/storage/docs/listing-objects#list-objects-json
The documentation gives this curl request
curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
reqConfig: this is a token I use in my REST firestore queries to authenticate the user. I'm using that same token for here. I'm guessing it's the problem but not sure how to fix it.
My result is consistently 404 for a bucket path that I know exists, using the URL from their docs. I should be getting a json list of the files in the bucket.
Error: Request failed with status code 404
Where am I going wrong?
export async function getCompanyStorage(context, apikey, companyId) {
const url = `https://storage.googleapis.com/storage/v1/b/uploads/${companyId}/o?key=${apikey}`;
const cookies = nookies.get(context);
const reqConfig = {
headers: new Headers({
Authorization: "Bearer " + cookies.token,
"Content-Type": "application/json",
}),
};
const result = axios
.get(url, { headers: { Authorization: `Bearer ${reqConfig}` } })
.then((res) => {
return res.data;
})
.catch((error) => {
console.error("error using axios", error);
});
}
Edit: a path to a bucket in the firebase console looks like this
gs://projectname.appspot.com/uploads/WhmDZyQdLVk7n0qR7aTg
I suggest reviewing the documentation you linked to. In particular:
OAUTH2_TOKEN is the access token you generated in Step 1.
BUCKET_NAME is the name of the bucket whose objects you want to list. For example, my-bucket.
You can use a prefix=PREFIX query string parameter to limit results to
objects that have the specified prefix.
Your URL does not contain the name of the bucket as required by the URL pattern. Use the unique name of the bucket where you see "BUCKET_NAME". It looks like, given your example, that it would be "projectname.appspot.com". BUCKET_NAME is not the path of the object within that bucket. If you want to list files under the "uploads" prefix, then you would use the prefix query string parameter to specify that, as documented in the last line of the quoted text.
You can use this function to create Get request with axios for Google Cloud Storage
export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
console.log(signedurl)
/*
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedurl);
xhr.setRequestHeader('Content-Type', "application/octet-stream");
xhr.send(file);
*/
let config = {
headers: {
'Content-Type': 'application/octet-stream',
},
};
await axios.get(signedurl, file, config).then(function (response) {
resultState.state = 'success';
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}

ionic 3 header not sending Authorizaqtion 'bearer "token"' to server

Im doing a login screen that takes a username and password.
if the login was successful the server will return a token.
then im trying to call another function to get user info but the authorization header is not being passed.
im trying my server method on postman and its working fine so i believe the problem is in the headers. May someone please advise me on what should be done?
let url = urlConst.Login;
let params1 = new HttpParams();
let loader = this.loadingcontroller.create({
content: stringEngConst.signinngin
});
let attributes = {
username: this.uname.value.toLowerCase(),
password: this.password.value,
grant_type: "password"
};
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = 'username=' + this.uname.value.toLowerCase() + '&password=' + this.password.value + '&grant_type=password';
let data: Observable < any > = this.http.post(url, body, {
headers: headers
});
loader.present().then(() => {
data.subscribe(result => {
if (result.access_token != null) {
this.signintoken = result.access_token;
this.storage.set(storageConst.SIGN_IN_TOKEN, result.token_type + " " + result.access_token);
headers.append('Authorization', 'Bearer ' + this.signintoken);
let url1 = 'http://localhost:57940/API/Account/GetUserInfo/';
let info: Observable < any > = this.http.get(url1, {
headers: headers
});
info.subscribe(result => {
/*Do Something*/
});
}
Please Note that result.access_token != null is true. and i am successfully getting the token back. But it is not being passed again to the second url (info)
Looks like this SO post may solve things for you: https://stackoverflow.com/a/47805759/6599076
You may want to use:
headers = headers.append('Authorization', 'Bearer ' + this.signintoken);
You are using the same headers as for the first http request:
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
Depending on your end point for the subsequent call it might be that you need to set headers differently:
Try creating new headers with
var headers2 = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Or get rid of Content-Type completely depending on what your end point expects.
Also if you are using Ionic 3 its worth to check which Http module you are using (HttpClient or the older one) as there are some differences in how these tend to handle request options.

Access TFS RESTful API from Angular web app

I think TFS RESTful api has a bug. I am trying to access it using an Angular web app. Our TFS server is corporate internal. Here is my code:
var path = 'http://tfs.mycompany.com/tfs/mycompany/_apis/wit/queries?$depth=1&$expand=all&api-version=2.2';
var config = { withCredentials: true };
$http.get(path, config)
.then(function (response) {
$scope.resultList = response.data.d.results || [ response.data.d ];
$scope.message = 'Found ' + $scope.resultList.length + ' item' + ($scope.resultList.length == 1 ? '':'s');
}, function (response) {
$scope.resultList = [];
$scope.message = 'Error ' + response.status + ' ' + JSON.stringify(response.data);
});
The request goes to the server, and the server responds with OK 200. However, the browser (Chrome) blocks the data, and tells me:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header
when the credentials flag is true. Origin 'http://localhost' is therefore
not allowed access. The credentials mode of an XMLHttpRequest is controlled
by the withCredentials attribute.
The request headers have Origin:http://localhost
The response headers have Access-Control-Allow-Origin:*
Is there any way for me to tell TFS to not return * in the Access-Control-Allow-Origin? This seems like a serious bug in TFS, which renders the RESTful api practically useless for web apps!
You may check Cross-origin resource sharing (CORS) example below to add Authorization in your code:
$( document ).ready(function() {
$.ajax({
url: 'https://fabrikam.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
}
}).done(function( results ) {
console.log( results.value[0].id + " " + results.value[0].name );
});
});
Also, check this case to see whether it is helpful:
AJAX cross domain issue with Visual Studio Online REST API

Making POST Requests in Backbone.js

I have a RESTful server, which accepts url encoded parameters.
In my case, making a post request to https:// my server:8443/test/auth
Set the request header as
Content-Type : application/x-www-form-urlencoded
and passing the parameters
username=myusername
password=mypassword
works and gives the desired response.
I want to achieve the same using Backbonejs. So, I have
Person = Backbone.Model.extend({
initialize: function() {
this.on('all', function(e) { console.log(this.get('name') + " event " + e );
});
},
urlRoot: "https:// my server:8443/test/authauth",
url : function(){
var base = this.urlRoot;
return base + ""
}
});
var person = new Person({ "username" : "myusername" , "password":"mypassword" });
person.save(null, {
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}}
);
But, it says that no username and password attributes are not present. Waht is the correct way to pass the paramteres in url encoded form in Backbone.js
Thanks

AngularJS ngResrouce REST Authentication

I'm trying to learn AngularJS. I'm try to make a simple authenticated get request to a REST api. At this point, i'm just trying to get a response back. I keep getting invalid key because I can't seem to send the headers properly.
angular.module('App', ['ngResource']);
function AppCtrl($scope, $resource){
$scope.app = $resource('https://theapiurl.com/parameter=:action',
{action:'My Parameter works fine!'},
{method: 'GET'},
{headers: 'auth-key' : 'key'});
$scope.app.get();
}
I just can't seem to get the header to send. Thanks for reading.
If you are using angular-resource 1.1.x+ the following should work:
angular.module('App', ['ngResource']);
function AppCtrl($scope, $resource){
$scope.app = $resource('https://theapiurl.com/parameter=:action',
{
action:'My Parameter works fine!'
},
{
get: {
method: 'GET',
headers : { 'auth-key' : 'key' }
}
});
$scope.app.get();
}
If you are using 1.0.x branch this won't work. I believe the only alternative is to set global default headers in $httpProvider, or to user $http directly (not using $resource). Here's how you would set the headers globally:
$httpProvider.defaults.headers.get['auth-key'] = 'key';
To avoid setting the header in every resource you could use an interceptor:
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'request': function(config) {
config.headers['auth-key'] = 'key';
return $q.when(config);
}
};
});
});