Angular 2 Http Get call with Basic Authentication - http

There are various questions related to the same concept, but somehow I am not able to figure out a simple HTTP Get call with Angular 2.
I have tried the same service with postman and it works, but not with a angular service.
My code looks like:
Service.js
let headers = new Headers({ 'Authorization': 'Basic ' + btoa('a#b.com:password') });
let options = new RequestOptions({ headers: headers });
return this.http.get(Config.Api.GetNavbar, options).map((res: Response) => res.json());
I get a 401 Unauthorized error even if I am setting the headers.
Any help?

I was facing exactly the same behavior when I was doing my first REST calls with Angular - it worked with Postman but didn't with Angular.
Some Browsers make a so called "preflight" call before the "real" AJAX call, and this first call caused the 401 Unauthorized response. The issue was that I was not allowing OPTIONS headers without authentication. The handling of OPTIONS headers was also in the restricted area but the authentication information was missing so the server send me back a 401 Unauthorized.
In the end the solution was to handle the OPTIONS requests outside of the restricted area. So the client receives now an OK for OPTIONS headers requests and goes on with the "real" call.
Since I have adjusted the request handling on server side everything works as expected.

Related

NextJS - fetch() works only inside getServerSideProps()

My fetch() method for making api requests works only when inside getServerSideProps() method.
For example I have api call for fetching a customer cart (and it is inside getServerSideProps):
const res = await fetch(apiUrl, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + jwtToken
}
});
And it works fine, I get response from api with customer cart. But when I try to make that api call on a button click, and when I move that inside button click handle method, then I get firstly:
Access to fetch at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
After that when I set mode to 'no-cors', then I get this:
GET ... net::ERR_ABORTED 400 (Bad Request)
So how it is possible that when inside getServerSideProps, there are no any CORS issues and everything is good, but when works on a button click then I get CORS issue and after that there is that other 'Bad request' problem.
Becuase by design browsers block the API request when the API response doesn't have Access-Control-Allow-Headers. But when you fetch the API inside getServerSideProps the the API request is made by Node.js server which doesn't check for Access-Control-Allow-Headers.
If you want to make this API request in browser then you can fix it by:
// If you can change the API code, here's an example to add the CORS headers in a netlify serverless function, this is the API response that I return from a serverless function
return {
statusCode: 200,
headers: {
/* Required for CORS support to work */
'Access-Control-Allow-Origin': '*', // you can add the domain names here or '*' will allow all domains
/* Required for cookies, authorization headers with HTTPS */
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify({
message: 'Hello from netlify'
})
}
or If your API backend is in Node.js and Express.js you can use cors npm package
if you don't have the access to change the API then try writing a wrapper API (or you can say a proxy API) that will make the API request and send it's response to you.
or If you just want the API request to happen for once only (on page load like componentDidMount) you can use the getServerSideProps.
For more detailed explanation on how to fix CORS error read
How does Access-Control-Allow-Origin header work?

HERE-maps CORS problems with Autocomplete

I want to use HERE maps autocomplete in my project.
But when a i send request like the one in documentation
this.axios.get('http://autocomplete.geocoder.api.here.com/6.2/suggest.json
?app_id={YOUR_APP_ID}
&app_code={YOUR_APP_CODE}
&query=Pariser+1+Berl
&beginHighlight=<b>
&endHighlight=</b>'
)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
i get an error
OPTIONS http://autocomplete.geocoder.api.here.com/6.2/suggest.json?{...} 405
Access to XMLHttpRequest at 'http://autocomplete.geocoder.api.here.com/6.2/suggest.json?{...}' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
In Chrome developer console in network panel i check this
Provisional headers are shown
Access-Control-Request-Headers: x-auth-token, content-type
Access-Control-Request-Method: GET
I set content-type in request headers to application/json and Provisional headers changed
to Access-Control-Request-Headers: x-auth-token
Access-Control-Request-Method: GET
So if i understand right, i should set x-auth-token header. But where can i take this token?
Or may be this problem has another reason?
There's nothing about such problems in documentaion.
The problem was simple and a bit stupid.
When user authenticated in my app I added default header to axios
axios.defaults.headers.common['X-Auth-Token'] = token
so this header was sended to all requests.
But HERE-map API doesn't want this header in requests and this was the cause of the problem.
The solution was to remove this header from requests to HERE-map API.
For those who have defined by default the header :
'Content-Type': 'application/json'
You must deactivate it, there should not be any HttpHeaders on the call request to Here API services.
temporary install Allow-Control-Allow-Origin google chrome plugin .. installed then you can show top right side click on that and switch the button then refresh then again call your api and get the response.

Authorization header not working Angular 5

I am consuming an JWT based API.
I am passing the Authorization header correctly (I mean in the code),
using headers.set('Authorization', 'token') and i am using the correct method which is GET.
When i serve the application (using ionic 3), i have the error 405 (Method Not Allowed), but the same request works when i use POSTMAN or i paste the code snippet (generated from POSTMAN) into the console.
Here's two captures of the working request (using code snippet from POSTMAN into the console) and the not working request (from the ionic app).
By the way, there is something weird about the authorization, i highlighted it in red.
If it is not a cors issue, you could try according to following code
const httpOptions = {
headers: new HttpHeaders()
.set('Authorization', 'Bearer ' +this.auth_token)
}
return this.http.get('http://xxxxxx00x:8080/api/clients',httpOptions);
On the top screen you have got request method OPTIONS not GET and response from the server is 405 Method not allowed not 401 Unauthorized or 403 Forbidden.
So the problem is not authorization but request method.
Looks like CORS issue.

Axios post request in react-native app

I'm using axios in my react-native app, but I can't make any POST request in android simulator/device. It always return 400 Bad Request from the server.
I've tried to set Content-Type: application/json on headers but it didn't work as well.
on postman the request works as expected.
here's the request config object:
As you know, 400 Bad Request error means that the request you sent to the website server was somehow incorrect or corrupted and the server couldn't understand it.
I think there maybe problems on your request like as wrong URL or params or header format...
PS. Axios post methods syntax is as follows:
axios.post(url[, data[, config]])
You can test any axios method here and put it into your code base after it works.

Fetch API, custom request headers, CORS, and cross-origin redirects

I need to make an HTTP GET request with custom request headers in-browser and process the result as it streams in. The Fetch API is ideal for this:
fetch('https://example.com/resource', {
method: 'GET',
headers: {
'X-Brad-Test': 'true'
},
cache: 'no-store',
mode: 'cors'
}).then((res) => {
const reader = res.body.getReader();
// etc.
});
This works quite well. Since there are custom headers, the browser pre-flights the request with an OPTIONS request to /resource. I have configured my server to respond with a 204 No Content and the following headers:
Access-Control-Allow-Headers: X-Requested-With, Range, If-Range, X-Brad-Test
Access-Control-Allow-Origin: *
The browser is happy with this, then makes a GET request, the server returns a 200 OK with the data, and the browser allows me to access the response headers and body.
The problem comes in when there is a redirect. The OPTIONS request succeeds with the 204 No Content and the same headers as before. The browser makes the correct GET request, and on the server I send a 302 with a Location: header. Chrome throws the following error:
Fetch API cannot load https://example.com/resource. Redirect from 'https://example.com/resource' to 'http://some-other-origin/resource' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
This was unexpected, and seems nonsensical to me. I expected the browser to follow the redirect, and do another pre-flight request for this new location, but it didn't do that.
Stranger still is that I can sort of hack around this client-side. I can make an HTTP request without my custom header, figure out where I ended up after redirects by looking at the Response object, then make a second request at the new target with my custom headers. This doesn't work in all cases of course, and I'd rather not rely on this hack. I'd rather find a proper way.
Two Questions:
What is the proper way to allow the client to follow redirects? Is there some sort of Access-Control-* header I can use?
Why does this restriction exist? What security issue is prevented by not following and running pre-flight on the followed URL?
Supporting redirects to requests that require a preflight is very recent change to Fetch (which defines CORS).
https://github.com/whatwg/fetch/commit/0d9a4db8bc02251cc9e391543bb3c1322fb882f2
I believe some implementations have started adjusting their implementations, but this will take some time to reach everyone.

Resources