How to send fetch post request to an API key based authorized endpoint?
10,271
Please correct me if I'm wrong.
fetch('api/Sessions', {
method: 'POST',
headers: {
'X-API-KEY': 'apikey',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(callData)
})
.then(response => response.text())
.then((response) => updateResponse(response))
.catch(error => console.error(error));
Related videos on Youtube
Author by
anonymous
Updated on June 04, 2022Comments
-
anonymous almost 2 years
I have a .netcore web API application with several endpoints and I have a simple UI built to access an endpoint with a button click using javascript fetch API.
fetch('api/Sessions', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(callData) }) .then(response => response.text()) .then((response) => updateResponse(response)) .catch(error => console.error(error)); }
Now the API endpoint in the controller is authenticated with API-KEY,
[ServiceFilter(typeof(AuthorizeKey))]
I can no longer access the endpoint from my UI. How can I change the HTML/javascript code in order to send the post request from my UI to the authenticated endpoint? Thanks-
MindSwipe almost 4 yearsPlease do not tag your questions with language tags not related to your problem
-
MindSwipe almost 4 yearsYou would do this using the HTTP Authorization header, but for that we need to know what kind of authorization your server is doing, is it bearer token auth? If so, then you need the header
'Authorization': 'Bearer <insert api key here>
-
anonymous almost 4 yearsIn the API, we are getting the API secret key from the header as
context.HttpContext.Request.Headers["X-API-KEY"];
. Therefore as per my understanding is it possible to add the key in the header and how to add it if it's possible? -
MindSwipe almost 4 yearsYes, your client side would simply need to add the "X-API-KEY" header to the request, with the value of your API key
-