Maintaining login session in Ionic

How can I maintain login session in ionic so that whenever a user is logged in ,user remains logged in until & unless user logs out from the app?

you can save your authentication data(username, password etc…) to either localstorage or sqlite then check it inside device ready function…

Example code:

var removeListener = $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {

		if (window.localStorage.getItem("username") === null && window.localStorage.getItem("password") === null) {
			if(fromState.name == '' ) {
				console.log('DENY');
            	$location.path('/index');
        	}
        }
        else if (window.localStorage.getItem("username") !== null && window.localStorage.getItem("password") !== null) {
        	//console.log('Next route: ', toState.name); 
            if(fromState.name == '' ) {
            	console.log('ALLOW');
            	$location.path('/lounge');
        	}
        }
        else {
        		
        }
    }); 

Here I check whether if my localstorage is empty and if it is it will go directly to my index page and if the localstorage has data it will go to my lounge page…

@anicacute09 As mentioned here:
https://ionicframework.com/docs/v2/2.0.0-beta.9/api/platform/storage/LocalStorage/

LocalStorage should ONLY be used for temporary data that you can afford to lose. Given disk space constraints on a mobile device, local storage might be “cleaned up” by the operating system (iOS). What should I use for login session?

Where should I actually store login credential?

You should never store sensitive data in local storage (and you should never store a user’s password anywhere except as a hash), this can easily be stolen. Instead, you can store some kind of token in local storage (like a JWT) to automatically log a user in if it is present. It’s fine to just use normal local storage for this kind of thing, although it can be cleared, it is rare - and in the rare event of local storage being cleared the user would just have to log in one more time.

If you absolutely don’t want the user to have to log in again, then just install the SQLite plugin and make sure to use Ionic’s Storage service.

2 Likes

Thanks @joshmorony for your suggestion. I am getting token(session id) from server that can be used in the similar way as you have suggested.

well as I mentioned earlier you can either choose localstorage or sqlite for storing your credentials. It is your choice and strategy on how to encrypt it for security purposes… Just giving you a hint on how to solve your problem… It’s your choice… Happy coding…