Implement Ionic cookie based authentication


#1

I research several days about cookie-based authentication .

I have a simple solution is :
App.js:

.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider, $provide, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.post[‘Accept’] = ‘application/json; q=0.01’;
$httpProvider.defaults.headers.post[‘X-Requested-With’] = ‘XMLHttpRequest’;
}

Sever(php):

 header('Access-Control-Allow-Origin: http://localhost:8100');
    header('Access-Control-Allow-Headers: X-Requested-With, X-API-KEY');
    header('Access-Control-Max-Age: 60');
    header('Access-Control-Allow-Methods: ["GET","POST"]');
    header('Access-Control-Allow-Credentials: true');

The sever is write with code igniter framework. When a user login the session can get correct value.

it worked well on IOS Simulator.

Access-Control-Allow-Origin: * will not be worked.So I change it to ‘header(‘Access-Control-Allow-Origin: http://localhost:8100’);’

When I use ‘ionic serve’ command it worked on Safiri or Chrome.

But I don’t know whether it is a good solution. When the official release app will be stable or not?

sorry bad english.


#2

This will not work on a real device, http://localhost:8100’ means nothing on the phone it’s just meaningful on your mac when using ionic serve.

Try this:

header('Access-Control-Allow-Origin: *');

#3

Thanks for reply.

header('Access-Control-Allow-Origin: *');

not working with localhost test.I tried run app on the real device.

header('Access-Control-Allow-Origin: *'); is ok.
even I remove:

header('Access-Control-Allow-Credentials: true');

this line with php, it still working well on the real device.I am confused.


#4

Anyone has a solution for this? I met similar problems.
But even in the Ionics’s blog. http://blog.ionic.io/angularjs-authentication/

It says: “One thing to note when using withCredentials: true in your app and configuring the server for CORS is that you may not have your Access-Control-Allow-Origin header set to ‘*’. It must be configured to a few select origins.”

But how can this be possible if I want to deploy this to a real device?
I have to set "Access-Control-Allow-Origin " to be “*”, and I need to use cookies as credential.


#5

@max
Hello, this is a very important issue with our app, as it was developed as angularjs app before in asp.net framework. We are trying to move it to ionic to build an app from it. But this authentication issue really blocks us.

Do we have to use token-based authentication for this?

Thanks!


#6

I think it works on the really app, as I just found out this post.
http://blog.ionic.io/handling-cors-issues-in-ionic/

Just need to do a proxy for ionic serve.