Angularjs "HTTP/1.1 401 Unauthorized" error in chrome - angularjs

I have an angularjs application which is consuming a WebAPI created using WCF.
Angularjs application is making call to a WebAPI to fetch client details.
When i run both the projects (angularjs and WCF project) on my local machine. Everything works fine.
After deploying the project on development server I am facing issue while testing my angularjs application in chrome. Chrome fails to load the client details.
I checked the requests made by angularjs application using fiddler. I found that there are two calls made my angularjs application to webAPI, even though in code there is only one call in code,
Following is the code used in angular app
return $http({
method: "GET",
withCredentials: true,
url: $rootScope.models.ServiceURL + "/ServicerClient?clientName=" + searchTextSmallLetters,
dataType: "json",
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
First request logged in Fiddler :
GET /PXTRAService.svc/ServicerClient?clientName=volvo HTTP/1.1
First request retunrs following error :
HTTP/1.1 401 Unauthorized
Next request logged in Fiddler has Security section in request header:
GET /PXTRAService.svc/ServicerClient?clientName=volvo HTTP/1.1
Second request retunrs the expected result.
Same scenario is occuring in IE, but IE angular application redeners the fetched results correctly.
Is there any way to fix this issue in chrome?

Related

ERROR 405 Method Not Allowed after hosting in IIS but works in development mode

I am using Web Api C# as backend for my application. I have enable CORS globally in the project.
config.EnableCors();
The frontend is developed in Reactjs. All the methods work in development mode but when I deployed the application in IIS, the post method does not work. I receive the following error message.
"Request failed with status code 405" Method not allowed"
Below is the api calling code.
axios(
{
method: 'POST',
url: URL,
data : JSON.stringify({partyid:'1234567'}),
headers: { 'content-type': 'application/json' }
}

calling Https url on Http get request angularjs

I have a Https url and want to send request to get data from that URL , scenario 1:
from my browser If I hit the Url i get the response whereas from my Angularjs App I get always an error 401 , but if I hit the Api from browser I always get the correct response
for security reasons I couldn't use Url here but what I want is to:
$http({
method: "GET",
url: "https://urlAdresss/",
headers: {
"Accept-Language": "en-US, en;q=0.8",
"Content-Type": "application/json;charset=UTF-8"
},
}).then(function (_response) {
console.log(_response
}
I always get unauthorized I am network as well as On console any help will be greatly appreciated ,
but If I hit the same Url from browser I get the response It means the backend is working fine
I think I am missing something in my get request that's why getting the error
It seems a CORS (Cross-Origin Resource Sharing) issue.
In AngularJS side, you should use the following configuration in order for $http service to automatically send authorization headers to http requests.
var app = angular.module('app', [])
.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
});
And in backend you should specify explicitly allowed origins (eg. http://localhost:8888).
Also, note some points from here.
If you want to allow credentials then your Access-Control-Allow-Origin must not use *.

How to make this Angular http get request (with basic authentication) work?

I am trying to debug my angular app with chrome dev console.I want to send a get request to a local server from angular. I've tried the following:
$http = angular.element($0).injector().get('$http');
$base64 = angular.element($0).injector().get('$base64');
var auth = $base64.encode("user:passwd");
var authHeaders = {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"};
$http.get("url",{headers:authHeaders,method:"GET"})
After reading this answer:
https://stackoverflow.com/a/30296149/1496826
I thought that custom header is the problem. So, I tried putting the authorization headers in the body:
$http.get("url",{data: {"Authorization": "Basic " + auth,"Access-Control-Allow-Origin":"*"},method:"GET"})
But I am still getting the same error:
XMLHttpRequest cannot load "url". No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'null' is
therefore not allowed access. The response had HTTP status code 401.
This same get request works fine from Postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "url",
"method": "GET",
"headers": {
"authorization": "Basic bWdhcasdasd",
"cache-control": "no-cache",
"postman-token": "XXXXXX-XXXXXX-xXXXX-xXXXX"
}
}
I have tried several other variation like - $http default / common header etc. but everything failed. Please help.
this is a CORS issue.
CORS headers must be handled server side, i don't see your server side code here but in order to let this error disappear you must specify which domain are allowed to request resources.
the exception is caused by the browser that intercept the server response check the headers and if it doesn't find the Allow-Control-Allow-Origin header it won't forward the response to your code (this happens only for cross origin request).
This is why Postman let you see the response, because it doesn't do what chrome does, doesn't make any check.
As i said the correct solution is to fix your server side code and specify the Allow-Control-Allow-Origin header , alternatively a quick but temporary workaround is to install this plugin for chrome that will intercept the server response and add the Allow-Control-Allow-Origin to * (means any domain) this trick will fool chrome and make you see the response.

Node/Express not finding route for Angular http json post (404)

I'm developing a new Angular client which should communicate with my Node/Express server. I'm currently trying to develop the first step aka the login. This should be an http json post. It turns out that every single time I execute that post from the client to the server, the Node/Express server doesn't find the route for my path.
On the console log of the server, for my post json request I find following stacktrace:
OPTIONS /api/auth/facebook/mobile 404 274.092 ms - 1980
Node/Express side:
My route
app.post('/api/auth/facebook/mobile', authenticationHandler.handleFacebookMobileLoginRequest);
Body parser for json is defined:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
On the Angular client side, I do:
http({
method: 'POST',
url: 'http://192.168.1.101:3000/api/auth/facebook/mobile',
headers: { 'Content-Type': 'application/json; charset=UTF-8;' },
data: {fbToken: authResponse.accessToken}
})
.then(function (response) {
...
Fun facts:
Same route works fine when I call it from a Java app or and Android native app, like
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SERVER_URL + "/api/auth/facebook/mobile", params, jsonRequestListener, errorListener);
On my Angular client, when I change data with params then it works, the route is found...but I mean that doesn't make any sense. Moreover, I've got then a problem on the Angular client side, the answer isn't processed respectively the answer never land in the .then(... function. Which again works well in other clients.
Anyone got an idea, a clue or should I call Dr. Strange?
Possible browser preflighted request CORS issue?
Try using CORS module in Node.js server:
var cors = require('cors')
app.use(cors());

Angular HTTP request blocked - Showing mixed content

Angular HTTP request is blocked - Showing mixed content.
But when i'm accessing through browser URL, the content is showing.
The angular code is:
$http.post('http://crms.ttteamthoi.in/get_timespent_br', {
'from': '01/11/2015',
'to': '25/11/2015'
}, {
"headers": {
"Content-Type": "application/json; charset=UTF-8"
}
})
.then(function(response) {
//code here
}
The console error showing is:
Mixed Content: The page at 'https://dash-thaidash.c9users.io/#/app/tonnage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://crms.ttteamthoi.in/get_timespent_br'. This request has been blocked; the content must be served over HTTPS.
Is this angular specific?
It does not seem to be Angular specific. crms.ttteamthoi.in host is telling you that accepts only https requests, but you POST some data using http protocol. Try using https.
You can simulate http requests here.
Problem Solved.
Server is asp.net application without SSL. The call was from https://c9.io which is secure. That was the mixed content error.
Changing the server application to SSL & then enabling CORS for content type did the trick.

Resources