How to send fetch post request to an API key based authorized endpoint?

Viewed 12580

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

1 Answers

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