Header not coming to service while Get Request is made from Angular - javascript

I have an angular JS application, from where I am calling a GET API. The API is OAuth 2.0 enabled, so requires a Bearer Token in the header. So, I am calling the http method like this:
var config = {
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': "Bearer XXXXXXX"
}
};
$http.get("http://host:port/api_call", config)
.then(function (response) {
return response.data;
});
But when I am making this call, I am getting 401 Unauthorized exception. Initially I thought of this as a CORS issue, So I whitelisted the origin to make call to the services host, but still didn't work. So, I checked the logs and found that Authorization header is not coming to the API application, though angular is sending the same.
Note: Is this the best way to make a service call from Angular?
I am quite new to Angular JS and thus have almost no idea how to diagnose or troubleshoot this type of issues. Can someone please tell me the possible errors/how to troubleshoot this?

The issue was in the API gateway. It was not able to make Cross Origin Calls and thus the API call was terminated there, hence Authorization header was not coming.

Related

How can I bypass CORS to make a call to Firestore from Blazor WebAssembly? (call is in in JavaScript) [duplicate]

This question already has answers here:
CORS error even after setting Access-Control-Allow-Origin or other Access-Control-Allow-* headers on client side
(2 answers)
Closed 1 year ago.
I am building a simple login page using Blazor WebAssembly and utilizing JSInterop to write JS functions in order to work with Firebase/Firestore. I have a function that signs the user in through a simple custom form using Firebase methods, then grabs the id token and user id to then pass into another function that requests access to Firestore. Everything works perfectly through Postman, but when I run through this process in my app, I am blocked by a CORS error:
Access to fetch at 'https://firestore.googleapis.com/v1/projects/trailblazor-
5ba6f/databases/(default)/documents/users/JJNlKtvGMcUm7MjfkuJy6WdlMiO2' from origin
'https://localhost:44318' has been blocked by CORS policy: Response to preflight request doesn't pass
access control check: It does not have HTTP ok status.
Here is my code for the request to access user data in Firestore (passing in the id token and user id):
async function sendToken(idToken, userId) {
try {
const response = await fetch(`https://firestore.googleapis.com/v1/projects/trailblazor-5ba6f/databases/(default)/documents/users/${userId}`, {
headers: new Headers({
'x-api-key': '**omitted for security**',
'Authorization': 'Bearer ' + idToken,
'Access-Control-Allow-Origin': 'https://localhost:44318',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json'
}),
mode: 'cors'
});
const receivedResponse = await response.json();
if (receivedResponse != null) {
console.log(receivedResponse);
}
} catch (error) {
return error.message;
}
}
As you can see, I've tried loads of headers and nothing has worked so far. Even the CORS-enabling Chrome extension I have enabled is not helping. I have thought about making a proxy server, but I'm not sure if that makes sense quite yet. I've reviewed the Firebase docs and this should be how I can access Firestore, and like I said, everything works flawlessly in Postman (of course).
Firstly, CORS is managed by the server. The fact that you add some header in your request doesn't help. It the server who, based on the domain of incoming requests, sets appropriate headers if CORS requests are allowed.
You're right about making a proxy server. You can use https://cors-anywhere.herokuapp.com/corsdemo, which is a proxy server for frontend developers to make CORS requests. The github page is here

Making Get request to Yammer API works using Postman tool but not with Vue-Resource

I am trying to integrate Yammer API in my Vue.JS project, for Http calls I am using Vue-Resource plugin. While making GET Http call to get posts from Yammer it gives me following error -
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I tried postman tool and that gives successful response, but when I try to run the same thing in my Vue.JS project using Vue-Resource plugin it wont work.
The Vue.JS code snippet -
function(){
this.$http.get("https://www.yammer.com/api/v1/messages/my_feed.json").then((data)=>{
console.log(data);
});
In main.vue file i have -
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer my_yammer_token')
request.headers.set('Accept', '*/*')
next()
})
Then I tried the code snippets provided by Postman tool for jquery, that too not working.
jQuery code -
var settings = {
"url": "https://www.yammer.com/api/v1/messages/my_feed.json",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer my_yammer_token",
"Cookie": "yamtrak_id=some_token; _session=some_token"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Though, I found similar questions but nothing worked for me.
I am working this to resolve from last 2 days but getting failed again and again. Please guide/help me.
A browser has higher security requirements than a request in PostMan. In a browser, you are only allowed to make XHR requests to your own current host (combination of domain + port) but not to other remote hosts. To nevertheless make a request to a remote host, you can use the browser built-in CORS. By using this, your browser makes a pre-flight request to the remote host to ask if the current page is allowed to request from that host. This is done via the Access-Control response headers. In your case, this header is probably missing or not allowing your page to access, which is why the request does not go through. Please read further into that topic.
However, in your case, using CORS probably won't be a solution for two reasons: To use CORS, the remote host must present a header which allows every requesting host (*) or your specific one. If you cannot set that setting anywhere on the remote host, it won't work. Second, it is not safe to place your authorization token into client-side JavaScript code. Everybody can just read your JS code and extract the authorization token. For that reason, you usually make the actual API call from the server-side and then pass the data to the client. You can use your own authentication/authorization against your server and then use the static authorization key on the server to request the data from the remote host. In that case, you'll never expose the authorization key to your user. Also, on the server-side, you do not have to deal with CORS as it works just like PostMan or curl as opposed to a browser.

HTTP Basic Authentication in AngularJS

I am trying to call an API in AngularJS. API has HTTP Basic Authentication with username = admin and password = admin123
This is how I am calling the API,
$http.get('https://example.com', {
headers: {'Authorization': 'Basic YWRtaW46YWRtaW4xMjM='}
}).then(console.log("something"));
But, it is giving me 401 UnAuthorized response. What is the recommended way to pass the username and password ? I am using AngularJS 1.
Error is showing,
OPTIONS https://example.com 401 ()
Failed to load https://example.com: Response for preflight has invalid HTTP status code 401.
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Authorization":"Basic YWRtaW46YWRtaW4xMjM=","Accept":"application/json, text/plain, */*"},"url":"https://example.com"},"statusText":"","xhrStatus":"error"}
You're probably going to want to set the authorization headers at a more global level if all of your requests are going to need it. You can do this by adding
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = '<Basic Auth Header>';
}]);
In your app config. To answer your actual question, I don't see anything specifically wrong with the code that you provided. Could you provide some information around what the server side is expecting and how it's reading the authorization?

"Header Not Allowed By Access-Control-Allow-Headers In Preflight Response" (React App)

EDIT: So I changed my code so that I'm handling the base64 encoding myself, which as one user noted, might be necessary.
Now I've encountered a new problem. I'm getting a CORS preflight error that looks like this:
Fetch API cannot load http://flightxml.flightaware.com/json/FlightXML2/FlightInfo. Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Correct me if I'm mistaken: This would imply that the server does not allow "authorization" headers within HTTP requests (which doesn't make any sense, seeing as the docs explicitly tell me to encode the username and API key and pass them as an auth header).
I saw some other posts about this issue, but since I did not build the server, I can't go in and make the change that allows auth headers.
Any new ideas? Thank you so, so much!
ORIGINAL POST:
I'm building a React app that integrates with the FlightAware API.
I made a FlightAware component for handling HTTP requests to the API. I want to start with a simple request to get information about a given plane flight. Unfortunately, I keep getting a 401 unauthorized response despite providing my credentials via state.
(I know this isn't best practices, I'm just doing it temporarily to get the request working.)
Any idea what I'm doing wrong here? Here's the code for the request:
componentDidMount() {
var form = new FormData();
form.append('ident', this.state.flightnum);
form.append('howMany', '10');
form.append('offset', '0');
fetch('http://flightxml.flightaware.com/json/FlightXML2/FlightInfo', {
method: 'GET',
auth: {
user: this.state.user,
pass: this.state.key
},
data: form
})
.then(result => {
// do something...
});
}

Preflight OPTIONS request returns status 405

I am currently developing a dashboard which consumes the Mention API. However, I am having difficulties due to the CORS policy.
If the dashboard is opened on Chrome or another browser that has a strict CORS policy, they make a preflight OPTIONS request each time, but these appear to not be supported by the Mention API.
Therefore, every time I do something like:
this.mentionAPI = axios.create({
baseURL: 'https://web.mention.net/api/accounts/my-account-id',
headers: {
'Authorization': 'Bearer my-access-token',
}
});
this.mentionAPI.get('/alerts')
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(response);
});
I get a response with the status 405 Method Not Allowed. This suggests that the OPTIONS requests are not handled by the Mention API at all.
Naturally, in my case I can just make sure that the browser is configured to not perform preflight requests. After all, my use case prescribes just one client, which I control completely. Alternatively, I could build a server-side service to make the requests on my behalf, however it seems like hunting a fly with cannon, since client side JavaScript is more than capable to perform everything else.
Any help on this issue would be really appreciated. Perhaps I'm misunderstanding how the API is intended to be consumed?

Categories