Read cookie in AngularJs, REST API - angularjs

So, I created my client application using angular to interact with my WCF REST API. I basically use cookies to store the login session and retrieve the information by sessions. This works perfectly from Postman and also with a console client application (there I created cookie container).
Now I have a problem to read the cookies from AngularJs. My HTTP response header shows the cookies but the angular response header is undefined.
AngularService.js:
this.login = function (credential) {
var request = $http({
method: "POST",
url: "someUrlLogin",
data: angular.toJson(credental),
config: { withCredentials: true },
});
return request;
}
AngularContoller.js :
var promisePost = AngularService.login(credential);
promisePost.then(function (response) {
$scope.loginResult = angular.fromJson(response);
$timeout(function () {
console.log(response.headers("Set-Cookie"); //null
console.log($cookies["ASP.NET_SessionId"]); //undefined
console.log($cookies.getAll); //undefined
},
function error (err) {
$scope.loginResult = err;
});
WCF REST session:
_context.Session["USERLOGGEDIN"] = "SomeValue"
I have set the HTTPOnly flag to false
I have also tried "console.log(response.headers("setcookie") which also doesn't work
"Access-Control-Allow-Credentials = true"
"Access-Control-Expose-Headers" value="content-type, Set-Cookie"
What else am I missing? Is it even possible to read the cookies from the http response headers?

Related

AWS S3: No 'Access-Control-Allow-Origin' header is present on the requested resource

In my angular app, I have the following error when I try to make an REST api.
My Code is given below:
Angular Controller
$scope.saveTeam = function() {
var club = {};
club.name = $scope.selectedClub;
var service = API.getService();
service.create( {}, { club: club },
function( res ) {
}, function(err) {
console.log("club err : ", err);
});
}
}
Angular Factory
// Clubs service used for communicating with the coaches REST endpoint
angular
.module('app')
.factory('API', ['$resource', 'session', function($resource, session) {
var mainUrl = '/clubs';
return {
getService : function() {
var token = session.getToken();
return $resource(mainUrl, { }, {
createClub: {
method: 'POST',
url: mainUrl,
isArray: false,
headers: { 'Token': token }
}
})
}
}
});
How can I solve this error? Thanks in Advance.
Install this chrome extension to avoid CORS error. This error generally comes because of the security headers in the request made by a client. Use the line of code shown below before making any request to server.
$http.defaults.headers.post["Content-Type"] = "application/json";
Working principles of CORS is a simple HEADERS game between Client and Server. The browser (the client) set in the Origin key the current domain in your case set "http://localhost:9001". The server, in turn, verified that this value is among those trusted and responds with another piece of information (always in the header) with the key Access-Control-Allow-Origin. If the two values are equal, then the browser uses the response, otherwise you will have an error.
So in the future you need to configure the server but for development you can start the Chrome browser with Disable same origin policy. With disable security the browser don't set the origin and you don't have a problem. This is the problem so check this link:
Disable same origin policy in Chrome

Drupal REST return 301 after logging in from ionic application

I have web application based on drupal 7, and I want to create ionic app connected with that web app using REST.
Login action work good, but after login I always get status 301 Moved Permamently, no matter what I call from REST.
But when I do the same using ARC or POSTMASTER all works good. I can call login successfully, get token successfully, and logout without any problem.
I guess the reason is not set header properly. When I use ARC or POSTMASTER my request contains Cookie with session_name and sessid received from drupal during login.
Also I cant set X-CSRF-Token in header.
But when I attempt to set it on angular nothing changes on request [headers are not set].
My login controller on ionic(angular):
var login = function(name, pw) {
return $q(function(resolve, reject) {
var data = "username="+name+"&password="+pw;
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}
$http.post('http://example.com/user/login.json', data, config)
.then(
function(response){
// success callback
storeUserCredentials(name + '.' + response.data.token, response.data.session_name, response.data.sessid);
storeUserRole(response.data.user.roles);
resolve('Login success.');
},
function(response){
// failure callback
//console.log('error '+response);
reject('Login Failed.');
}
);
});
};
My logout controller on ionic(angular):
var logout = function() {
var data = "username="+name+"&password="+pw;
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-CSRF-Token': token,
'Cookie':session_name + '=' + sessid
}
}
$http.post('http://example.com/user/logout.json', data, config)
.then(
function(response){
// success callback
destroyUserCredentials();
},
function(response){
// failure callback
destroyUserCredentials();
}
);
};
This technique works for me
I store the 'minimal' config object as a starting point. This object is created using the response from /services/session/token as the data in the following:
localStorageService.set('HTTP_CONFIG', {
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': data
}
});
Contrary to many examples online, I find it unnecessary to set the cookies manually. In fact, attempting to set cookies often results in errors. In this example I'll use local storage to produce copies of the http config.
Next, I ascertain if I'm logged in or not.
var tokenConfig = localStorageService.get('HTTP_CONFIG');
tokenConfig.url = APP_CONFIG.REST_API + '/system/connect.json';
tokenConfig.method = 'POST';
tokenConfig.data = {};
$http(tokenConfig) ...
I simply carry forward in this manner, for instance:
var loginConfig = localStorageService.get('HTTP_CONFIG');
loginConfig.method = 'POST';
loginConfig.url = APP_CONFIG.REST_API + '/user/login';
loginConfig.data = { username: username, password: password };
$http(loginConfig) ...
I simply carry forward using the same 'minimal' http config object, adding properties as required. This has worked perfectly for me.

Token authorization - Browser throws Login form

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

Getting 401 error when call $http POST and passing data

I am calling a Web API 2 backend from an angularjs client. The backend is using windows authentication and I have set up the $httpProvider to use credentials with all calls and it works fine for all GETS.
Like this:
$httpProvider.defaults.withCredentials = true
But, when using the POST verb method AND passing a data js object I get a 401 error. If I remove the data object from the $http.post call it reaches the endpoint but I would like to pass up the data I need to save.
Here's an example of the client-side call:
var saveIndicator = function (indicator) {
var req = {
method: 'POST',
url: baseUrl + "/api/indicators",
data: indicator
};
return $http(req).then(function (response) {
return response.data;
});
};

Angular $http post with custom headers

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

Resources