I am sending a post auth request from my localhost to a remote server to get response cookies returned by server(using ionic proxy to solve CORS). From chrome network inspector, I can see the response cookie has been returned from server. However, I am not able to access it from $http post response. I try almost everything from other posts and I still can not get the cookie. What I have tried
I use ngCookie and $timeout combination. Basically I get an empty object when I use $cookie.getAll() which I assume the cookie is not there
I also set withCredentials to true
I also tried headers.get('set-cookie')
My angular version is 1.5.3. Please help
Below is my code
angular.module('starter.controllers', ['ngCookies'])
.controller('DashCtrl', function($scope, $http, $cookies, $timeout) {
$http({
method: 'POST',
url: '/api/User/Authenticate',
data: {
Username: 'xxx',
Password: 'xxx'
},
withCredentials: true
}).then(function(response) {
$timeout(function() {
console.log($cookies); // return {}
console.log($cookies.getAll()); // return {}
});
}, function(response) {
});
})
Here is the server response
Related
I have Restfull API (localhost:8180) which is having secure authentication. Using Angular JS http (or other services) I need to login into that server and get my data from localhost:8180/api/version/?1 (this is just example) Please find my code below.
//configure file
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
//setting cookie
app.run(['$http', '$cookies', function($http, $cookies) {
$http.defaults.headers.post['JSESSIONID'] = $cookies.JSESSIONID;
}]);
// My Controller
$http({
url:'http://localhost:8180',
method:'POST',
data: {
username:'adminadmin',
password:'passpass'
},
headers: {
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Credentials": true,
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "*/*",
'Authorization': 'Basic adminadmin:passpass' // I guess its wrong
}
})
.success (function(){
console.log("Success");
//Need to call my API here
})
.error(function(data, status, headers, config){
console.log("Failed");
});
Here I'm getting No Access-Control-Allow-Origin and Origin null
error. If success I need to call localhost:8180/api/version?1 inside
of the success method using get or post. Here my server is
localhost:9596. I need to call 8180 host from 9596 host and get the
data into 9596 host.
Whenever you are getting Cross-origin Error, you need to as the server guys to add some headers sent while sending responses back to the ajax request.
Basing on Backend you need to use different approach to making this change in server:
In Java Tomcat Server: You need to configure filter mapping
Source : http://enable-cors.org/server.html
I want to send the document cookie in the http call in angular.
I have already used withCredentials but it can only send the browser level cookie.
I also use the cross domain ,but it is not working fine.
Below is the code which I am using.
$http({
method: 'GET',
url: url,
xhrFields: { withCredentials: true },
crossDomain: true,
header:{ 'SHOPSESSIONID' : sessionStorage.getItem("SHOPSESSIONID") }
}).success(function(data){
return data;
}).error(function(data){
return data;
});
use $httpProvider in config phase:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}])
and you could give up the xhrFields and crossDomain proporties
btw, angular uses then instead of success, and catch instead of error. (that is the promise syntax)
I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});
I was trying to access api running in localhost using angular $resourses, chrome console gives me error saying ERR_INSECURE_RESPONSE.
I tried disabling web security in chrome. still same error. here is the angular factory that i used. How can I bypass this error and test my app.
ImpactPortal.factory('apiFactory', function ($resource) {
return $resource('https://localhost:8443/mifosng-provider/api/v1/client_impact_portal', {}, {
query: {
method: 'GET',
params: {},
isArray: true
}
})
});
Enabling CORS in Angular.js
var myApp = angular.module('myApp', [
'myAppApiService']);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
A server supporting CORS must respond to requests with several access control headers:
Access-Control-Allow-Origin: "*"
By default, CORS requests are not made with cookies. If the server includes this header, then we
can send cookies along with our request by setting the withCredentials option to true.
Access-Control-Allow-Credentials (optional)
If we set the withCredentials option in our request to true, but the server does not respond
with this header, then the request will fail and vice versa.
Only try this:
Go to https://[your-domain].com and then chrome block you with the famous page:
Your connection is not private
So go down to ADVANVCED and then proceed.
Your certificate is probably self-signed.
Remember to do that for each Chrome session.
You must authenticate first and then send each request along with the auth token.
I am using RestAngular so my settings might look a little different from what you are working on.
This will go in your application config :-
RestangularProvider.setDefaultHeaders({ 'X-Mifos-Platform-TenantId': 'default' });
and something like this will go in your controller/service
var login = Restangular.all('authentication?username=mifos&password=password').post().then(function(user) {
console.log(user);
}, function() {
console.log("There was an error saving");
});
Error 501 (net::ERR_INSECURE_RESPONSE) - 501 Not Implemented
The server either does not recognize the request method, or it lacks the ability to fulfill the request. Usually this implies future availability (e.g., a new feature of a web-service API).
Can you confirm that curl request is working fine
curl -k --user damien#email.com:password https://localhost:8443/mifosng-provider/api/v1/client_impact_portal
If it is working fine:
ImpactPortal.factory('apiFactory', function ($resource) {
return $resource('https://localhost:8443/mifosng-provider/api/v1/client_impact_portal', {}, {
query: {
method: 'JSONP',
params: {},
isArray: true
}
})
});
Try following this tutorial that consume an external API: http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app
I'm trying to retrieve Cookies using the $cookies service provided by ngCookies but I keep getting 'undefined', I really don't know what it's wrong...
I can clearly see the cookie displayed in the Dev Console in Chrome.
AND I also set a XSRF-TOKEN cookie and Angular's $http is NOT including it as a Header (X-XSRF-TOKEN) which I think it's the same problem.
Laravel by default encrypts Cookies and are extremely long, could that be it?
If I set a cookie with the $cookies service, it appears and I can retrieve it withou issue, so the $cookies service is working.... :P
angular.module("MachinatorApp.Services.SectionService", [])
.factory("SectionService", ["$http", "$cookies", function($http, $cookies) {
console.log($cookies.laravel_session);
var doRequest = function(action, id) {
var params = $.param({
"action" : action,
"id" : id
});
return $http({
method : 'POST',
url : "/Sections/" + action,
data : params,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
return {
sections: function(action, id) {
return doRequest(action, id);
}
}
}]);
I found out what the solution was by looking a the Laravel API Documentation, Cooke::make() by default sends a HttpOnly cookie, that's why I could not read it from Angular, Adding false to the httpOnly parameter fixes the issue, Although Now I think it's just safer to leave it http only and read from the header's cookies.
http://laravel.com/api/4.1/
search for Cookie, click CookieJar, make method
Cookie::make("XSRF-TOKEN", Session::token(), 0, null, null, null, false))
This sends a NON HTTP ONLY Cookie which you can read from angularJS