AngularJS $http custom headers not working - angularjs

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

Related

Response for preflight has invalid HTTP status code 405 on Angular Js1 and Webapi 2

Error:
OPTIONS http://localhost:8080//api/home/GetText 405 (Method Not Allowed)
http://localhost:8080//api/home/GetText. Response for preflight has invalid HTTP status code 405
angular.js:14362 Error: Error getting home/GetText data from the database!
Headers:
Response Headers:
Access-Control-Allow-Credentials:false
Access-Control-Allow-Headers:gid,Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET
Content-Length:76
Content-Type:application/json; charset=utf-8
Date:Fri, 28 Jul 2017 10:30:06 GMT
Server:Microsoft-IIS/10.0
X-Powered-By:ASP.NET
Request Headers:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:authorization,gid
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://evil.com/
Pragma:no-cache
Referer:http://localhost:1852/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Please note that i am using Angular Js as client and Webapi for server side. I am performing xhr request through $resource service.
This is because your back-end API doesn't support OPTIONS request for your routes (specifically /api/home/GetText this route). AngularJS typically checks CORS requests by issuing OPTIONS requests prior to making actual content requests.
You need to enable support for OPTIONS requests at your back-end, and return appropriate headers + good HTTP status (200-299) from there.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "gid, filename, Origin, X - Requested - With, Content - Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "X-filename");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
This fixed the above issue.
it Means that your're tryng to call a method from FRONT END TO BACK END with the WRONG HTTP VERBS (so for example PUT INSTEAD of POST)
double check it

Angular js get request with headers- showing CORS error

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.

Cross origin issue with ajax, angular and Zuul

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);
}

AngularJs - Adding custom parameter to Request Header

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.

CORS preflight returns 200 but subsequent PUT never happens (Angular JS with external REST API)

I'm working with an Angular app that talks to a REST api.
I have set up access-control so that my GET requests are working as expected. (The browser sends a preflight OPTIONS request and then the subsequent GET fires).
However, I am running into problems with my PUTs.
The problem is that with PUTs the options preflight seems to return okay but then the PUT never fires.
First I will show what works and then what is failing. I am using Charles to spy on the calls.
GET (working)
1) preflight request
OPTIONS /v1/account HTTP/1.1
Host api.mysite.com
Access-Control-Request-Method GET
Origin http://127.0.0.1:9000
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Access-Control-Request-Headers accept, authorization
Accept */*
Referer http://127.0.0.1:9000/
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8
2) preflight response
HTTP/1.1 200 OK
Server nginx/1.6.0
Date Wed, 21 May 2014 15:43:25 GMT
Content-Type application/octet-stream
Content-Length 0
Connection keep-alive
Access-Control-Allow-Origin *
Access-Control-Allow-Methods *
Access-Control-Allow-Headers Origin, X-Requested-With, Content-Type, Accept, Authorization, WWW-Authenticate, X-BLURR-DEBUG
Access-Control-Allow-Credentials true
3) The GET request
GET /v1/account HTTP/1.1
Host api.mysite.com
Accept application/json, text/plain, */*
Origin http://127.0.0.1:9000
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
AUTHORIZATION DFHD8D...
Referer http://127.0.0.1:9000/
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8
4) The GET response
{ some json as expected }
PUT (not working)
Now, here is the PUT that seems to return an okay preflight response but never gets to the PUT request:
1) preflight request
OPTIONS /v1/account HTTP/1.1
Host api.mysite.com
Access-Control-Request-Method PUT
Origin http://127.0.0.1:9000
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36
Access-Control-Request-Headers accept, authorization, content-type
Accept */*
Referer http://127.0.0.1:9000/
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8
2) preflight response
HTTP/1.1 200 OK
Server nginx/1.6.0
Date Wed, 21 May 2014 15:51:41 GMT
Content-Type application/octet-stream
Content-Length 0
Connection keep-alive
Access-Control-Allow-Origin *
Access-Control-Allow-Methods *
Access-Control-Allow-Headers Origin, X-Requested-With, Content-Type, Accept, Authorization, WWW-Authenticate, X-BLURR-DEBUG
Access-Control-Allow-Credentials true
The problem
It seems that the preflight response for the PUT is okay, so I'm not sure why the browser never sends the actual PUT request.
Any help or direction would be great! Thank you
The * (star) is not a valid value for the Access-Control-Allow-Methods header. You need to list the actual methods (e.g. GET, PUT). It seems like although the preflight response is successful from the server, the browser is probably still rejecting the preflight and not sending the actual request. Check the browser's console log for any errors.

Resources