How to fetch elasticsearch api with auth - javascript

i try to fetch elastic api using javascript with basic authentication, but there is error show that request header field authorization is not allowed by acccess-control-allow-headers, is it something wrong with the elasticsearch api or the wrong is on my code? i already setting enable cors on elastic, i tried curl to get elastic data with auth and it works, does the fetch code is wrong?
the console error :
the fetch code :
fetch('http://192.168.150.220:9900/', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('em_user:3md#t#2o22')}})
.then(response => response.json())
.then(json => console.log(json));

To use fetch from your browser, you will have to allow cross-origin requests in the ElasticSearch configuration:
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization
http.cors.allow-credentials: true
Source:
https://www.elastic.co/guide/en/elasticsearch/reference/8.2/modules-network.html
https://www.elastic.co/guide/en/cloud-enterprise/current/ece-configure-cors.html

Related

Flask API with CORS error in delete method

I have developed a rest api in Flask. All my api endpoints work fine when I test them with postman.
Now, I am developing an application with Javascript that consumes the resources of my api.
I'm having trouble consuming an endpoint that works with the delete method. Endpoints with get and post work fine, but not the delete method. I get the next CORS error:
Access to fetch at 'http://localhost:5000/contacto' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
This is my Javascript code:
let data ={id: id};
let url = "http://localhost:5000/contacto";
fetch(url, {
credentials: 'include',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
alert(res.result);
});
On the server side, I use flask_cors. I configure the app with this code:
from flask import Flask, jsonify, request
from flask_cors import CORS
import controllers.userController as userController
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
#CORS(app)
#CORS(app, resources={r"/*": {"origins": "*"}}, send_wildcard=True)
CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})
The path of my service with delete method is this:
#app.route('/contacto', methods = ['DELETE'])
def deleteContacto():
parametros = request.args
id = parametros['id']
result = contactController.eliminar_contacto(id)
response = None
if result == True:
response = jsonify({'result':'Contacto eliminado con éxito'})
else:
response = jsonify({'result':'Error al eliminar el contacto'})
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response
I need some help. I have searched and tried many possible solutions but they do not work for me. I'm a bit desperate.
Thanks in advance and regards.
I do this a bit different, but make sure you have this option set to allow delete and options methods:
'Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'
I add them manually to the response object in flask
resp.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
CORS should be setting this as a default, but maybe something is misconfigured?
see the docs:
https://flask-cors.readthedocs.io/en/latest/configuration.html

Firebase Realtime Rest API with JavaScript

The Firebase Documentation has some useful curl operations but doesn't provide information regarding Cors, headers, and auth using JS Fetch. We are using a fetch-only solution as I am creating a client-based Firebase npm package where users might not have the firebase modules imported for several reasons, tree shaking, minified project, etc.
I imagine I need to pass on the Auth as a header, What about Cors and credentials?
Here is a crude example, is this sufficient? or are there other unforeseen issues?
const pushOptions = {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
var dataAPI = await fetch(databaseUrl+`/test.json`,pushOptions)
.then(response => response.json())
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://firebase.google.com/docs/reference/rest/database#section-put
The documentation says you need to pass your Firebase ID in query parameter 'access_token' and not in any header. For example,
curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?access_token=CREDENTIAL'
But I ended up getting Unauthorized errors.
However, the Authenticate with an ID Token section in Firebase Auth REST API documentation says, "pass the ID token generated above as the auth=<ID_TOKEN> query string parameter". A sample curl request for the same would be:
curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?auth=CREDENTIAL'
This request worked as expected.
About CORS, this answer says,
Firebase uses a fully-permissive cross-origin resource sharing (CORS) policy, meaning that you can make requests to the Firebase servers from any origin. This is possible because Firebase does not use cookies or traditional sessions to govern which requests are authorized and which are not.
Here's a working example using Javascript fetch:
firebase.auth().onAuthStateChanged(async (user) => {
const token = await firebase.auth().currentUser.getIdToken()
const pushOptions = {
method: 'GET',
}
const reqURL = "https://[PROJECT_ID].firebaseio.com" + `/path.json?auth=${token}`
const dataAPI = await fetch(reqURL, pushOptions)
.then(response => response.json())
.then(res => console.log(res))
})
I just used the client SDK to get an ID Token quickly but it will work irrespective of from where the token is generated - client SDK or Auth REST API.
The REST API accepts the same Firebase ID tokens used by the client SDKs.

Using SpreadShirt REST API with JavaScript / Fetch

What i try to do
I have a small ReactJS application. In this application, i try to do an REST request to the API of SpreadShirt via the JS Fetch API.
What fails
Basically i get no data. The console of the browser shows the following output:
Access to fetch at 'https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
My Code
getData() {
const header = new Headers({
"Authorization": "SprdAuth apiKey=\"XXXXXXXXX"",
"User-Agent": "MukoSoft/1.0 (https://mydomain.de; my#mail.de)"
});
const options = {
method: 'GET',
headers: header
};
fetch('https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json', options)
.then(response => response.json())
.then(data => this.setState({ data: data }))
.then(() => this.setState({ loading: false }))
}
Does anyone has a hint for me, while i can't fetch via JavaScript? And can somebody explain, why the request via Postman works, but not via fetch API?
Since this is my first question on stack overflow, you can give me advices on how to formulate questions better

CORS policy problem in react js client side

I created a Formik login form and call to react js fetch method. Add cors in web api end and successfully run in Postman and jquery. How to call "token_type": "bearer", through react js? cors is also enabled in web api and also generate Token successfully. How to call this url https://localhost:44323/token through react js?
My code is
onSubmit={(values) => {
fetch('https://localhost:44323/token', {
method: 'POST',
header: { 'Content-type': 'application/json,multipart/form-data' },
data: JSON.stringify(values)
})
.then(r => r.json())
.then(res => {
console.log(res)
});
}}>
Error messages
The root cause of the problem can be found in the following error message shown:
"Access to fetch at https://localhost:44323/token from origin http://localhost:3000 has been blocked by CORS policy. No Access-Control-Allow-Origin header is present on the requested resource ...."
How to fix the problem?
The problem can be fixed in these ways:
1. Allow the origin (http://localhost:3000) on the server (Recommended)
This can be done by adding the following header to HTTP response on the server side:
Access-Control-Allow-Origin: http://localhost:3000
2. Send Fetch request in the 'no-cors' mode
This can be done by updating the fetch request as follows:
fetch( 'https://localhost:44323/token',
{
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}
)
.then(response => {
// Code for processing the response
}
)
.catch((error) => {
// Code for handling the error
}
)
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Getting 401 Error code while using fetch() with a custom header

===
I've built a custom API with AWS API Gateway.
For one of the method, I've enable the authorization to be checked using a Lambda function.
In order to make it work, I have to add the following key: Key: authorizationToken Value: allow.
I've tested it using Postman and it's working fine, my POST is processed and I receive a response.
I'm just starting with Javascript so I've used the code provided in Postman.
Here it is:
function getData(event){
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
mode: 'no-cors'
};
fetch("https://[THE_URL_OF_MY_API]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
And i'm getting the following error message in the console.
script.js:49 POST https://[THE_URL_OF_MY_API]/prod/counter
net::ERR_ABORTED 401 (Unauthorized)
getData # script.js:49
I've looked into the logs of the API Gateway in AWS in order to troubleshoot it:
But I can't see any logs so it seems my fetch is being block before
it's even being sent.
I checked the headers of the successful API call sent by Postman and I can't find any header apart from mine and the one generated by the application automatically.
What am I doing wrong ?
Note: I'm using similar code to another endpoint where the authorization is not enabled and it's working fine. SO I guess my header is not correctly set.
Thanks !
#CRice, Salmin Skenderovic, Jaromanda X : Thanks a lot for your feedback.
The missing myHeaders was a typo, I fixed it.
Seeing the comment about the 'no-cors', I've looked into it, enable CORS, authorized my specific header in Access-Control-Allow-Headers.
And now it's working fine.
My amended code:
var myHeaders = new Headers();
myHeaders.set("authorizationToken", "allow");
var requestOptions = {
method: 'POST',
redirect: 'follow',
headers : myHeaders
};
fetch("https://[URL_OF_MY_API_ENDPOINT]/prod/counter", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Configuration of my API Gateway:
Configuration of my API Gateway

Categories

Resources