Http with token in Ionic 4 - ionic4

(Sorry for my bad english) I have to access an api, with a token that they have provided me. My problem is that I don't know how to implement it, after searching and searching, it gives me the following error:
Access to XMLHttpRequest at 'https://www.presupuestoabierto.gob.ar/api/v1/credito' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I pass my code to you, to indicate that it is wrong in the definition of the token (the x instead of the token) and eventually in the CORS policy, thank you very much!
const headers = { 'Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8100'}
this.http.get<any>('https://www.presupuestoabierto.gob.ar/api/v1/credito', { headers }).subscribe(data => {
this.datos = data.blabla;
})

Headers should pass like this in Ionic- Angular. Make sure that you have a service file.Visit this link to know more about services:
https://angular.io/tutorial/toh-pt4
let headers = new Headers({
'Content-Type' : 'application/json',
'Auth':authvalue
});
return this.http.get(url,options).pipe(map(res => res.json()));

Related

Axios request to AEM servlet redirecting to login.html

I have a working servlet that tests properly with Postman, but I can't get the request to execute from the front end. The fact that Postman can execute the servlet with either a Get or a Post tells me the problem is likely with the front-end code.
Does anyone see where the misconfiguration is in this block? The Basic key and cookie are copied from Postman, there is no CORs problem.
const response = await axios.get(url, null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Accept': '*/*',
'Content-type': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
withCredentials: true,
Cookie: "cq-authoring-mode=TOUCH;",
params: {
path: rootPath,
maxCount: sourceMax
}
}).catch(err => {
console.log(err)
}, () => {
console.log(response)
}).then(res => {
console.log(res)
})
This is most likely the CSRF filter which rejects some requests that don’t contain a CSRF token. By default it checks only POST, PUT and DELETE requests.
It’s weird that it also checks your request, which seems to be a GET. Either your filter is configured differently or you sending a Content-type header – which describes the request body content type – makes axios switch the request from GET to POST (because GETs don’t have a request body and, thus, don’t need to declare their content type).
The CSRF filter can be configured in various ways and can exclude certain requests from filtering by path or user-agent:
You could also request a token from the /libs/granite/csrf/token.json endpoint and then send it along in your request. One way to do this is via the query, as the :cq_csrf_token param.

Make https request with Postman with Bearer token like different user would make it

Hi all!
I'm trying to solve a bit of load testing.
Our API has throttling on that particular endpoint, but requests are disctinted by user, the system solve from the provided token.
When I trying the same scenario from different windows/browsers the throttling is working as expected but when the request sent from Postman the response is 429.
Tried the header "Connection":"close", and disabling the "User-Agent" and not allowing the cookie reuse (ARRAffinity is by default because of azure).
Tried already to run two separate request, where the first is the token request with a user then the actual request to the endpoint where the throttling is enabled.
Tried also to send the request then in the Test part as a callback after the token request sending the request to throttled endpoint like that:
pm.test("got token", function() {
let token = pm.response.json().accessToken;
pm.expect(token).to.not.be.null;
const exportRequest = {
method: 'POST',
url: `${pm.environment.get("base_URL")}/api/Export/Gtin/Excel`,
header: {
"accept": "text/plain",
"Authorization": `bearer ${token}`,
"Content-Type": "application/json-patch+json",
"Connection": "close"
},
body:JSON.stringify({
"companyPrefixId": "098102700",
"exportType": "EveryKeys",
"includeProductInfo": true,
"productInfoLanguageCodes": null,
"exportFileMainLanguageCode": "en"
})
};
pm.sendRequest(exportRequest, (err, response) => {
pm.expect(response).to.not.be.null;
if (err) {
console.log(JSON.stringify(err));
}
});
});
I hope someone can help to solve that, thanks in advance!
Best regards

CORS don't work after JWT authentication added

I have a Vue frontend, an Auth0 and Fastify backend. CORS is configured as follows:
fastify.register(require('fastify-cors'), {
origin: 'http://localhost:8080',
methods: 'GET,PUT,POST,DELETE,OPTIONS,HEAD',
allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
})
Frontend headers configuration:
this.$auth.getTokenSilently().then(token => {
this.headers = {
Authorization: `Bearer ${token}` // send the access token through the 'Authorization' header
};
The problem is common:
Access to XMLHttpRequest at 'http://127.0.0.1:3000/dir' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read a lot about CORS, know this is a browser side problem (Insomnia sends requests perfectly). Actually, I do not have clear understanding of what else I should allow and how. Basically I need only standart GET, PUT, POST, DELETE requests allowed. Could you please point out the exact configuration problems in my code?
First 401 was caused by OPTIONS request without autentication token. Actually it should be seamlessly processed by a fastify-cors. But due to an incorrect order of initialisation of on-request hooks (first - mine to autenticate, using fastify-auth0-verify, second - implicit hook from fastify-cors), it never invoked. So you need a precise order of hooks explicit and implicit initialization: first - cors, then second - authentication.
The second problem, 401 on the following POST, happened because of incorrect usage of an axios request params on the frontend Vue side. Headers like { Authorization: 'Bearer SomeVeryLongSecretXYZ'}were passed as, for instance, ...post(url, data, this.headers), but there must be {headers : this.headers}.
Final configuration for CORS:
fastify.register(require('fastify-cors'), {
origin: '*',
methods: 'GET,PUT,POST,DELETE,OPTIONS',
})

Testing external API's using Angular 2 & Apache

I am trying to make an HTTP requeset to an external API using the following request:
let headers = new Headers({
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': "*"
});
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify({
test: test
comments: "test"
});
this.http.post("EXTERNAL_API_URL", body, options)
.map(res => res.json())
.subscribe((data) => {
console.log(data);
});
When I am making the API call from Chrome Postman plugin, the API works without any problem.
When I'm trying to make this call from my angular 2 app, the call is not working and returns the following error:
XMLHttpRequest cannot load MY_API_URL. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
I know that I can access bypass it using the no web-security chrome:
Chrome.exe --disable-web-security
But I wish to make it work without it...
I also tried to add Header set Access-Control-Allow-Origin "*" in my http.conf as described here.
Any ideas?

Vue Resource Cross-site HTTP request

Normally, when I make a jQuery request to a non-local server, it applies Cross-site HTTP request rules and initially sends an OPTIONS request to verify the existence of an endpoint and then it sends the request, i.e.
GET to domain.tld/api/get/user/data/user_id
jQuery works fine, however I would like to use Vue Resource to deal with requests. In my network log, I see only the actual request being made (no OPTIONS request initially), and no data is being received.
Anybody has an idea how to solve this?
Sample Code:
var options = {
headers: {
'Authorization': 'Bearer xxx'
}
};
this.$http.get(config.api.base_url + 'open/cities',[options])
.then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
jquery-request
Solution:
As #Anton mentioned, it's not necessary to have both requests (environment negligible). Not sure what I have changed to make it work, but the request gave me an error. It consisted in setting the headers correctly. Headers should not be passed as options but as a property of http:
this.$http({
root: config.api.base_url + 'open/cities', // url, endpoint
method: 'GET',
headers: {
'Authorization': 'Bearer xxx'
}
}).then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
Thank you guys, it was a team effort :)
Is it a requirement that an additional OPTIONS request is being made? I have created a small (32 LOC) example which works fine and retrieves the data:
https://jsfiddle.net/ct372m7x/2/
As you can see, the data is being loaded from a non-local server. The example is located on jsfiddle.net and the request is made to httpbin.org - this leads to CORS being applied (you can see the Access-Control-Allow-Origin header in the screenshot below).
What you also see is that only the GET request has been executed, no OPTIONS before that.