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));
Share:
10,271

Related videos on Youtube

anonymous
Author by

anonymous

Updated on June 04, 2022

Comments

  • anonymous
    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
      MindSwipe almost 4 years
      Please do not tag your questions with language tags not related to your problem
    • MindSwipe
      MindSwipe almost 4 years
      You 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
      anonymous almost 4 years
      In 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
      MindSwipe almost 4 years
      Yes, your client side would simply need to add the "X-API-KEY" header to the request, with the value of your API key