I have zuul server implemented which does the routing to all my microservices. I have a seperate UI project which is in angular. I am trying to make an AJAX call from the UI app to a specific microservices which routes through Zuul but I am getting this error.
XMLHttpRequest cannot load http://localhost:8006/user/v1/userassociations. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 403.
But When I directly try to hit the api in local host which is hosted at http://localhost:4444/user/v1/userassociations it works perfectly fine. I have the below CORS configuration added to the actual api.
#Override
public void addCorsMappings(final CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
}
The problem is only happening when i try to hit the api via zuul I tried to add the same configuration to Zuul but it is not working.
I know it is the same origin issue but there must be a solution our microservices are suppose to go public so anyone can make the request from any domain.
Below is the Working AJAX call:- if i change the url to http://localhost:8006/user/v1/userassociations which is via zuul i get the cross origin.
var service = {};
service.userContextCall = function()
{
return $http({
url:'http://localhost:4444/user/v1/userassociations',
method: 'GET',
headers: {'Content-Type':'application/json',
'userContextId':'1234567890123456'}
}).success(function(response){
return response;
}).error(function(error){
return error;
});
};
return service;
Header that Iam receiving for when i hit the api via Zuul.
Request URL:http://localhost:8006/user/v1/userassociations
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:8006
Response Headers
view source
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:20
Date:Tue, 23 Feb 2016 18:51:15 GMT
Server:Apache-Coyote/1.1
X-Application-Context:apigateway:8006
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, usercontextid
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8006
Origin:http://localhost:63342
Referer:http://localhost:63342/icpAccountHolder/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
Header when i direclty hit the api the working one.
Request URL:http://localhost:4444/user/v1/userassociations
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:4444
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:63342
Content-Type:application/json;charset=utf-8
Date:Tue, 23 Feb 2016 18:54:19 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Origin
X-Application-Context:userassociations-v1
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:4444
Origin:http://localhost:63342
Referer:http://localhost:63342/icpAccountHolder/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
userContextId:1234567890123456
Can anyone help me with this.
The fix seems to be using the ANGEL.SR6 spring cloud version instead of BRIXTON. But In case you want to use Brixton this is what i wrote to override the CORS filter in Zuul.
#Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource= new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowCredentials(true);
corsConfig.addAllowedOrigin("*");
corsConfig.addAllowedHeader("*");
corsConfig.addAllowedMethod("OPTIONS");
corsConfig.addAllowedMethod("HEAD");
corsConfig.addAllowedMethod("GET");
corsConfig.addAllowedMethod("PUT");
corsConfig.addAllowedMethod("POST");
corsConfig.addAllowedMethod("DELETE");
corsConfig.addAllowedMethod("PATCH");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfig);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
Related
Ill try to keep this short to save digital rain forest. Please ask If I missed any details.
I have an "asp .net 3.1 core + react"-project template in VS, with built in Identity server. This works ok, but I now want to do my react project in a separate project. So I started a new create-react-app-project.
So, from my new react project, when I call OidcConfigurationController. The controller method is called and I can step through the code on server side. Then I get a client error "Failed to fetch", which, by internet wizdom, seems to indicated CORS-error.
This is what I got when I inspect the header in chrome dev toolbar->network
Request URL: https://localhost:5001/authentication/_configuration/MyProject.Web
Referrer Policy: strict-origin-when-cross-origin
:authority: localhost:5001
:method: GET
:path: /authentication/_configuration/MyProject.Web
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,sv;q=0.8
origin: http://localhost:3000
referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"
sec-ch-ua-mobile: ?0
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
These are relevant lines in startup.cs
ConfigureServices()
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
//builder.WithOrigins("http://localhost:3002/", "https://localhost:3001")
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowAll = true
};
});
Configure()
app.UseCors(MyAllowSpecificOrigins); // I also tried to switch order on these 2 rows
app.UseIdentityServer();
Nothing I do here seems to change the Referrer Policy in the header, still get the exact same message
The React-call is just a plain fetch(address-of-the-controller-that-it-hits).
I have also tried to start a new Server Side-project (asp net core api) and set same CORS-policy, I can call this api from my react client without getting any errors)
So, in the request, you see the origin: http://localhost:3000 header is used. That is the source for the CORS request. But the request is for this URL:
https://localhost:5001/authentication/_configuration/MyProject.Web
Could it not be that there's a redirect from insecure HTTP to HTTPS that is interfering?
Do make sure you set the CORS settings in IdentityServer as well.
See the CORS documentation for more details.
As side note, IIS might cause CORS issues as well, see this answer for details:
IIS hijacks CORS Preflight OPTIONS request
In my angular controller code my http get method not working with header but the same request working in postman
$http({
method: 'GET',
url: 'http://localhost:8080/api/profiles',
headers: {
'Authorization': 'Bearer 78954642-sf25-4sd6-sdf2-99582369d5af',
'Content-Type':'text/plain'
}
}).then(function(success) {
console.log(success);
}, function(error) {
});
Showing following error
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://quotebuilder' is therefore not allowed access. The response had HTTP status code 401.
My request header
OPTIONS /api/profiles HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://quotebuilder
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://quotebuilder/login
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
What is wrong here ? please help me to resolve the issue
Your should make CORS disabled in your server side to make this work. A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves see dtails here. If you are using spring or other server side web frameworks you need to disable that from there.
I'm having a bit of a problem trying to make a GET request.
This is what I'm trying:
var config = {headers: {
'Authorization': 'Basic ZGllZ28uY2FsYXphbnNAZ3J1cG9udC5jb20uYnI6MTIz',
'grupont.auth.idescola':'409651',
'grupont.auth.usercontext':'blahblah#blah.com.br'
}
$http.get('http://localhost:8585/api/rest/contratosAdesao/cursosConsoleTO/29526757', config).success(function(){}).error(function(){});
I'm trying to get some basic information from the server. This is the Request Header:
Accept:*/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, get,grupont.auth.idescola, grupont.auth.usercontext
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8585
Origin:127.0.0.1:43013
Pragma:no-cache
Referer:127.0.0.1:43013/cursos.html
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
I'm also getting this as a General Header:
Request Method:OPTIONS
Status Code:401 Unauthorized
The grupont.auth.idescola and grupont.auth.usercontext get added to Access-Control-Request-Headers.
Does anyone knows what it it happening? I'm trying to make a CORS call to a server, and I need to send some parameters on the Request Header.
Any help is much appreciated.
So, if anyone else has the same problem, the issue was with the server (jboss) response to the CORS request. It has to respond correctly to the preflight OPTIONS request.
If I send the GET Request with these parameters on the Header Request:
'withCredentials':true,
'Authorization': 'Basic ZGllZ28uY2FsYXphbnNAZ3J1cG9udC5jb20uYnI6MTIz',
'grupont.auth.idescola':'409651',
'grupont.auth.usercontext':'blahblah#blah.com.br'
The server needs to respond with:
Access-Control-Allow-Headers:grupont.auth.idescola,grupont.auth.usercontext,withCredentials,authorization
Access-Control-Allow-Origin:*
Allow:GET, OPTIONS, HEAD
And then the process can continue.
Hope it helps someone.
I'm struggling with this issue since many hours... :-(
My grunt-served angular app issues an $http GET request to a simple PHP service on the same host (apache), to get a list of persons. The result I get is an OPTIONS request (???), which gets a 405 response... But why an OPTIONS pre-flight request before a GET???
These are the details of my setup:
Grunt config Gruntfile.js:
grunt.initConfig({
...
connect: {
options: {
port: 9000,
hostname: '0.0.0.0',
livereload: 35729
},
},
...
Angular service persons.js:
app.service('Persons', function($http) {
...
return({
getPersons: function () {
return $http({
method: 'get',
url: http://192.168.1.1/myapp/api/persons/get',
}).then(handleSuccess, handleError);
},
...
});
...
File /api/persons/get/index.php:
...
header("Access-Control-Allow-Origin", "http://192.168.1.1:9000");
header("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
header("Access-Control-Allow-Headers", "GET, PUT, POST, OPTIONS, DELETE, X-XSRF-TOKEN");
echo json_encode($persons);
(In fact, server-side I use Slim framework, so this is "index.php" file, which serves "/api/persons/..." requests via .htaccess: "... RewriteRule ^(.)$ index.php [QSA,L]"...*)
And this is the (sad :-() result I get:
Remote Address:192.168.1.1:80
Request URL:http://192.168.1.1/myapp/api/persons/get
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,it-IT;q=0.6,it;q=0.4,tr;q=0.2,de;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:192.168.1.1
Origin:http://192.168.1.1:9000
Pragma:no-cache
Referer:http://192.168.1.1:9000/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Response Headersview source
Allow:GET HEAD
Connection:close
Content-Length:0
Content-Type:text/html;charset=UTF-8
Date:Fri, 30 Jan 2015 11:36:43 GMT
Server:Apache/2.2.15 (CentOS)
Set-Cookie:PHPSESSID=a5dbcfa18fcb64a29dbad999c6811d69; path=/
Set-Cookie:a5dbcfa18fcb64a29dbad999c6811d69=DEFAULT%7C0%7C2M3TMlgUx3gTlaarYzHIdD28l8q9FTcNubt55%2BUGpAo%3D%7C7456bf61db3500c8bb7b3bc38082a470ce4a2ad3; path=/
X-Powered-By:PHP/5.6.4
I did also try using grunt-connect-proxy, with no better results...
If I forgot any detail, please just ask...
Any clue?
It's a CORS preflight is mandatory for cross domain request.
The OPTIONS call actually return the list of available method (GET, POST, etc..).
You should allow the OPTIONS call on your php backend :
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
See there CORS not working php
I'm trying to add a custom header to an HTTP request but AngularJS does not seem to handle it. Here is my code:
$http({
method: "GET",
url: 'http://localhost:8080/Schedule-service/login',
headers: {
'X-AUTHENTICATION': 'TRUE'
}
}).success(function (response) {
$cookies[constants.TOKEN] = response.hash;
}).error(function (data, status, headers, config) {
});
I have tried to add this to the default headers but still nothing. What is wrong here?
Edit:
My request in the middle of doing GET:
Request URL:http://localhost:8080/Schedule-service/login
Request Headers CAUTION: Provisional headers are shown.
Access-Control-Request-Headers:accept, x-authentication
Access-Control-Request-Method:GET
Origin:http://localhost
Referer:http://localhost/ScheduleWebClient/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36
And after GET:
Request URL:http://localhost:8080/Schedule-service/login
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Request Headers:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, x-authentication
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost
Referer:http://localhost/ScheduleWebClient/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36
Response Headers:
Access-Control-Allow-Headers:origin, content-type, accept, x-requested-with, sid, mycustom, smuser
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Content-Length:0
Date:Fri, 24 Jan 2014 20:33:23 GMT
Server:GlassFish Server Open Source Edition 3.1.2.2
Set-Cookie:JSESSIONID=5f4fc0d1318a2e63cd1ca9170386; Path=/Schedule-service; HttpOnly
X-AUTHENTICATION:*
X-Powered-By:Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)
It seems you're performing CORS request and the request you pasted is preflight request. The application is working on port 80 but you're calling service on port 8080 hence its CORS cross origin. In the response above you see that the server will accept x-requested-with header
Access-Control-Allow-Headers:origin, content-type, accept, x-requested-with.
The header should be visible in the next request