CORS problems using angularjs $http - javascript

I get problems when using angularjs $http in a CORS request, my success function authenticateSuccess(data, status, headers) get wrong headers. As we know, every CORS request will be twice in angularjs, I get twice response from server, the first time is the cors validation information, the second is needed response, but my success function get the headers in the first response. But it's data is from second response.
function login(credentials) {
var data = {
username: credentials.username,
password: credentials.password,
rememberMe: credentials.rememberMe
};
console.log(data);
return $http.post('//localhost:8080/api/authenticate', data).success(authenticateSuccess);
function authenticateSuccess(data, status, headers) {
console.log(headers());
console.log(data);
var bearerToken = headers('Authorization');
if (angular.isDefined(bearerToken) && bearerToken.slice(0, 7) === 'Bearer ') {
var jwt = bearerToken.slice(7, bearerToken.length);
service.storeAuthenticationToken(jwt, credentials.rememberMe);
return jwt;
}
}
}

You are getting this problem as header which you are sending is not matched with the headers in backend
So let suppose In frontend you sending headers
contentHeaders = new Headers(); contentHeaders.append('Authorization', 'your token'); contentHeaders.append('Content-Type', 'application/json'); contentHeaders.append('Access-Control-Allow-Origin', '*');
So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.
So in backend 'Access-Control-Allow-Headers' should have all above headers see below
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");
So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.
It will work perfectly when you use above concept.
Thanks

Related

Authorized Firebase request to Cloud Functions HTTP return preflight request does not pass control check (No Access-Control-Allow-Origin)

I am trying to send authorized Firebase requests to HTTP Cloud Functions following the official documentation.
However, I keep getting the error message:
Access to XMLHttpRequest at '[CLOUD-FUNCTION-SOURCE-URL]' from origin
'http://127.0.0.1:8080' 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.
I tried the following:
def cors_enabled_function_auth(request):
# For more information about CORS and CORS preflight requests, see
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
# for more information.
# Set CORS headers for preflight requests
if request.method == 'OPTIONS':
# Allows POST requests from origin * Authorization header
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': ['Authorization', 'Content-Type'] ,
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Credentials': 'true'
}
return ('', 204, headers)
# Set CORS headers for main requests
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
}
print('core logic here')
return ('Hello World!', 200, headers)
On the front (using AngularJS) I make a request as follows:
self.getDownloadUrl = function(gcs_reference) {
var url = '[CLOUD-FUNCTION-URL]';
var params = {'param1': 'hello'};
var headers = {
'Content-Type': 'application/json'
}
return firebase.auth().onAuthStateChanged().then(
function (user) {
headers['Authorization'] = user['refreshToken']
return postRequestHTTP(params, url, headers)
},
function (error) {
console.log('error', error)
return error;
}
)
};
function postRequestHTTP(params, url, headers) {
// Generic HTTP post request to an url with parameters
var q = $q.defer();
var body = params;
var req = {
headers: headers
};
$http.post(url, body, req).then(
function(response) {
q.resolve(response)
}, function(error) {
q.reject(error)
}
);
return q.promise;
}
Does anyone know what is the cause of this heresy?
I can't reproduce this. With your function and a request like:
function reqListener () {
console.log(this.responseText);
}
xhr = new XMLHttpRequest();
xhr.open('POST', "[CLOUD-FUNCTION-URL]");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.addEventListener("load", reqListener);
xhr.send('test');
I get a successful request. Perhaps the latest version of your function is not actually deployed, or your frontend is pointing at a different endpoint?

Angular 6 Http request fails with authorization headers

I'm deploying and angular 6 application that works with a tomcat server in localhost, when I try to execure this http request
this.http
.post<LoginResult>( API_URL + '/login', JSON.stringify(json)/*, { headers: myHeader }*/).pipe(
catchError(this.handleError('get-token', []))).subscribe((response) => {
if(response['result_code'] == 'result_ok') {
this.auth.doSignIn(response['token'], response['name']);
this.router.navigate(['user_manager']);
return true;
}else {
return false;
}
});
everitying works well, but when I add header field
let myHeader = new HttpHeaders().append("Authorization", 'Basic' + this.session.getAccessToken());
this.http
.post<LoginResult>( API_URL + '/login', JSON.stringify(json), { headers: myHeader }).pipe(
catchError(this.handleError('get-token', []))).subscribe((response) => {
if(response['result_code'] == 'result_ok') {
this.auth.doSignIn(response['token'], response['name']);
this.router.navigate(['user_manager']);
return true;
}else {
return false;
}
});
this is my output error:
Access to XMLHttpRequest at 'http://localhost:8095/login' from origin 'http://localhost:4200' 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.
HttpErrorResponse
I checked also that the request doesn't arrive to my tomcat server, it is blocked before, that oesn't allow angular to check response headers
Thank you for your help
I'm providing you a generic answer as you have not mention that your server side code is written in which language. You should provide a header from your server code. Provide Access-Control-Allow-Origin header with value as localhost:4200 which will resolve your issue. Or if you want to allow every origin then change its value from localhost:4200 to *.
After reading all the comments I have change something for you.
change your this code let myHeader = new HttpHeaders().append("Authorization", 'Basic' + this.session.getAccessToken()); with const myHeader = new HttpHeaders({'Authorization': 'Bearer ' + localStorage.getItem('api_token')});
and make your post request as
this.http
.post<LoginResult>( API_URL + '/login', json, myHeader).pipe(
catchError(this.handleError('get-token', []))).subscribe((response) => {
if(response['result_code'] == 'result_ok') {
this.auth.doSignIn(response['token'], response['name']);
this.router.navigate(['user_manager']);
return true;
}else {
return false;
}
});
You need to configure CORS on your tomcat server.
You need to tell tomcat which headers the application is allowed to send, so it can include it in the preflight response:
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Authorization,Content-Type,...</param-value>
</init-param>
Take a look at
cors.allowed.methods under CORS Filter section here:
https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

How do I access response headers using HttpClient in Angular 5?

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.
My request looks like this:
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
})
.toPromise()
.then(response => {
console.log(response);
return response;
});
}
How do I access the authorization header of the response?
When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.
Any help is very much appreciated.
To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json'),
observe: 'response'
})
.map(res => {
let myHeader = res.headers.get('my-header');
});
Docs

Angular2 - Cross-Origin Request Blocked

I'm trying to use the forecast API with my angular2 app. However, when i try to access the API I get a Cross-Origin Error. Any idea how i can fix this error ?
search(latitude: any, longitude: any){
console.log(latitude);
console.log(longitude);
let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude ;
console.log(body);
this.http.get(body)
.map(
response => response.json()
).subscribe(
data => console.log("Data: "+data),
err => console.log("Error: "+err),
() => console.log('Get Complete')
);
}
Error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.forecast.io/forecast/APIKEY/37.8267,-122.423. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Update
Now using JSONP
let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude + '?callback=?' ;
console.log(body);
this.jsonp.get(body)
.map(response => response.json())
.subscribe(
data => console.log("Data: "+data),
err => console.log("Error: "+err),
() => console.log('Get Complete')
);
Error
Error0.def29191127bbc3e0100.hot-update.js:59:10
Object { _body: "JSONP injected script did not invok…", status: 200, ok: true, statusText: "Ok", headers: Object, type: 3, url: "https://api.forecast.io/forecast/60…" }0.def29191127bbc3e0100.hot-update.js:61:10
SyntaxError: expected expression, got '==='
For forecast.io, you should use JSONP. The easiest way to do this using jQuery is adding ?callback=? to request URL:
$.getJSON('https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + "?callback=?", function(data) {
console.log(data);
});
I am no expert on Angular 2 but reading the docs it looks like you need to import the Jsonp and then add a callback. More documentation here -- see the section app/wiki/wikipedia.service.ts.
I think something like the code below will work for you
let body = "https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + '?callback=?'";
return this.jsonp
.get(body)
.map(response => <string[]> response.json()[1]);
Check out the cors bits on angular.io
https://angular.io/docs/ts/latest/guide/server-communication.html#!#cors
Something like the below (from above)
return this.jsonp
.get(wikiUrl, { search: params })
.map(response => <string[]> response.json()[1]);
You are getting this problem because the header you are sending does not match the headers in the backend.
Suppose you send the following headers:
contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Your token used in app');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');
So those headers like Authorization, Content-type, and Access-Control-Allow-Origin should match the allowed headers in your backend.
So in the backend Access-Control-Allow-Headers should have all above headers:
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, content-type, Access-Control-Allow-Origin");
So here in Access-Control-Allow-Headers you have to pass all headers which you send from frontend: 'Authorization', 'Content-type', and 'Access-Control-Allow-Origin'.
It will work perfectly when you use above concept.
Hope this post will helpful for you
Thanks

Javascript Fetch not getting a response

I'm invoking an authentication service via javascript fetch to get an access token. The service is a simple RESTful call. I can see the call is successful using fiddler (with a 200 response and json data). However the fetch response never seems to get invoked. Below is a snippet:
const AUTHBODY = `grant_type=password&username=${username}&password=${password}&scope=roles offline_access profile`
const AUTHHEADER = new Headers({'Content-Type': 'application/x-www-form-urlencoded'})
const CONFIG = {
method: 'POST',
headers: AUTHHEADER,
body: AUTHBODY
}
fetch('http://localhost:23461/connect/token', CONFIG).then(function(response) {
console.log('response = ' + response)
return response.json()
}).then(function(json) {
console.log('json data = ' + json)
return json
}).catch(function(error) {
console.log('error = ' + error)
})
When executing the fetch above none of the console.logs gets executed... seems to just hang. But fiddler tells otherwise. Any ideas?
You probably met with the CORS origin policy problem. To tackle this you need some rights to access the server side of your API. In particular, you need to add a line in the header of php or another server endpoint:
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
Also, make sure NOT to have in the header of your server endpoint:
header("Access-Control-Allow-Credentials" : true);
Model of working fetch code with POST request is:
const data = {
message: 'We send a message to the backend with fetch()'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});

Categories

Resources