AngularJS ngCookies Ionic cookie is undefined - angularjs

My app is scraping data from a third party site wherein it needs to be logged in first before it could scrape the data. The thing is, there is a session expiration so the app needs to check if the session is already expired. If the session is not yet expired, $http's JSESSIONID cookie will be the same as the one returned after logging in. If it is expired, the value of JSESSIONID changes.
What I'm planning to do is that after logging in, I'll store the JSESSIONID to the localStorage. After every request of $http, I'll compare the new JSESSIONID to the stored JSESSIONID. I'll relogin the user if it's not the same(means session is expired).
However, I couldn't get the cookie. It returns undefined. I'm also thinking, is it because the cookie is on the request header instead of the response header? If yes, how could I get it?
$http({
method: 'POST',
url: url,
data: params
}).then(function (response) {
console.log($cookies.get('JSESSIONID'));
callback.success(Parser.getGrades(response.data));
}, function (error) {
callback.error();
});
I already included ngCookies, no errors but the value is undefined.
I tried to use getAll() and it returns:
Object {_ga: "GA1.1.1725476839.1445841661"}
Configurations of my $httpProvider:
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

Related

Should I send username and password in each request after authentication along with token?

I am using default guard api in Laravel and for front end i am using angularjs.
Angular Js code to fetch data from server
$http({
header: {
'Content-Type': 'application/json'
},
url: apiUrl + "apiViewProfile?api_token=" + $cookies.get("Token"),
method: 'POST'
});
after fetching the result in front end, I changed username and password in database manually. but I am still able to fetch results because of token.
Should I send Username and password also in each request along with token?
No. What you can do is invalidate the token once user changes his username/password.
If you are just saying that you logged in to a different user - in this case you must clear the cookie.
Nope. You need to just pass the token only. not need username and password
Info
You just store your token on your backend and set some time for clear the token. So once you reach the time, the token will be clear and religion the screen.

Using secure https and returning data

I am using a 3rd party API as a booking portal. I am using Angular $http to post to a php curl script on my site that will make the actual call cross site to the API.
factory.bookingRequest = function(reservationData){
return $http({
method: "post",
url: "api-book.php",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: reservationData
}).then(function(response){
return response.data;
});
};
1)
Does the Angular page that is posting to the php page need to be via https also? Or just the script that is responsible for sending the data outside of the site?
2) Also when I get the response back, it has a confirmation number and other details that they have said also need to be via HTTPS.
How would this best be handled? Could I have this as a session cookie and return it to a /booking/confirmation route or return this back to the same page but using ng-show or ng-hide to show confirmation details?
3)
Also when I am sending form data from my Angular route to my Php page in the network tab in chrome dev tools I can see all the information that is getting sent to my php page (Request payload in the headers tab). Just wanted to make sure this was ok also?

How do cookie authentication on couchdb with angularjs

Hey? Can someone hep me to do cookie authentication on CouchDB with AngularJS?
This my code:
var app = angular.module('app', []);
app.controller('mainController', ['$scope','$http', function($scope,$http){
//Authentification cookie
$http.({
url: 'http://localhost:5984/_session',
method: 'POST',
headers: {
Accept: 'application/json',
Content-Type: 'application/x-www-form-urlencoded'
},
data:{
name: "packy",
password: "packy8"
}
}).then(function(response){
console.log(response.headers);
});
}
The problem? i'm not able to read The AuthSesssion Cookie.
Cookies are sent via HTTP headers. If you got a cookie in response you have to dig into the response headers.
Alternatively you can ask the browser via JavaScript to provide the cookie data that was stored automatically from the response into the browser session.
To receive the AuthSession cookie from CouchDB you need to do a POST request to _session. The cookie you get is marked with a HttpOnly flag so it's tricky if not impossible to read it from the browser (at least I wasn't able to).
Once you have the cookie, GET requests to _session will return the logged in user, you don't need to do anything else. The one issue that I ran into was tricking the browser into prompting the "save password for this website" message, it seems they expect the POST request to be made from a standard HTML form not an ajax request. What I ended up with is a mix between sending a POST request using the Angular $http, then if successful do a full form request to _session as well as setting the "next" query param so I get returned to whatever page I need (otherwise you get stuck on the localhost:5984/_session page).

AngularJS Access Token Security Concerns

What is the best practice for storing an access token in AngularJS after it is retrieved from an authorization server? I have seen many suggestions to use the localStorage service, but then I have read other posts/blogs that say to never use localStorage to store tokens, it is not secure etc.
I am having a hard time wrapping my head around security with Angular because of mixed information like above.
I think,
Generate the token (sensitive info at server side)
Sign and Encrypt the generated token with machine key which is only known to server. And get the encrypted token.
Then save the encrypted token obtained at step2 in cookies.
Cookies expiration should be very less. Make httponly cookie.
When authenticating the cookie
Validate the cookie
Decrypt with machine key and verify it is sent by our server only and with the same crc.
Authenticate the obtained token if step2 above is good.
Angularjs Automatically add headers in each $http request,
AngularAppFactory.GetApp=function(appName){
var app = angular.module(appName, []);
app.factory('httpRequestInterceptor', ['$rootScope', function($rootScope)
{
return {
request: function($config) {
if( $rootScope.user.authToken )
{
$config.headers['id'] = $rootScope.user.id;
$config.headers['auth-token'] = $rootScope.user.authToken;
}
return $config;
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
return app;
}
//Whenever you need to get new angular app, you can call this function.
app = AngularAppFactory.GetApp('appName');

Authentication using Angularjs

I am fairly new to AngularJS
I have a resource that I use for user management which is part of a service following this article.
Once sending the login request to the server I am getting a response with a set-cookie as part of the header.
What is the best practice to add this cookie to every request I am sending to the server?
myApp.factory('UserService', ['$resource', function ($resource) {
var userRes = $resource('http://<MyDomain>/api/v1/user/:param',
{param: '#param'},
{
login: {
method: 'POST'
},
logout: {
method: 'DELETE'
}
});
var user;
return {
signIn: function () {
user = userRes.login({param: 'login'}, {"email": "SomeName#MyDomain.com", "password": "test1"});
userRes.get({param: '1'});
},
userRes.login has set-cookie header in on the response
userRes.get does not send the cookie that was just received.
Cheers
Since your API is in a different domain you can't use cookies in this case. We've tried and we failed to put it simple there is no way, not only it doesn't work with CORS but also it doesn't work if you embed an iframe. The iframe trick fails on safaris mostly but it is not reliable.
What we usually do is to return a JWT (Json Web Token) from the API and attach a header then to every API request as Authorization: Bearer JWT.
This JWT can be decoded using a public key from the front end (and it will contain the user profile) and validad with a private key in the backend.
JWT is simple and there are plenty of libraries for every language/technology.
Auth0 is an authentication broker that can validate with any identity provider or custom databases, and it returns JWTs using standars. It provides a clientID that can be used to decode the profile in the front end and a secret to validate the tokens in the backend as well as client side library to do this.
Disclaimer: I work for auth0.

Resources