Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store user session in AngularJS?

I have just started using AngularJS and I'm trying to store user session on my AngularApp.

First step to submit username and password works. After that, I store the username retrieved from the service in the $rootScope. The next page can display the username stored.

But after a refresh, the $rootScope is empty.

I'm trying to do an authentication system as simple as possible.

myApp.controller('loginController', ['$scope', '$rootScope', '$location', 'AuthService', '$route',
  function ($scope, $rootScope, $location, AuthService, $route) {

      $scope.login = function (credentials) {
        AuthService.login(credentials).then(function (response) {
          if(response.data == "0"){
            alert("Identifiant ou mot de passe incorrect");
          }
          else {
            // response.data is the JSON below 
            $rootScope.credentials = response.data;           
            $location.path("/");
          }
        });
      };

}]);

AuthService.login() makes a $http request.

JSON

 {user_id: 1, user_name: "u1", user_display_name: "Steffi"} 

HTML :

 <div>Welcome {{ credentials.user_display_name }}!</div>

I tried a lot of tutorials, but I can't make session work. I already used UserApp but it's not ok to me. I would like to create my own simple authentication.

like image 941
Steffi Avatar asked May 15 '14 15:05

Steffi


People also ask

How to store value in session using AngularJS?

You will have to serialize your Javascript object as session storage only supports strings. The getItem method key should be the same as it was for setItem. In your case emp-key . It should be var data = sessionStorage.

What is session storage in JS?

Introduction to JavaScript sessionStorage The sessionStorage object stores data only for a session. It means that the data stored in the sessionStorage will be deleted when the browser is closed. A page session lasts as long as the web browser is open and survives over the page refresh.

What is session storage?

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends. Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab.

Can we use session in angular?

It can only be used in a modern browser. When the window is closed or reopened while in session storage, the data is retained; however, when the tab is closed, the data will be lost. It's easy to create a new Angular project create a new Angular project using a command.


3 Answers

You can use

ngStorage

An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage.

Differences with Other Implementations

No Getter 'n' Setter Bullshit - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.

sessionStorage - We got this often-overlooked buddy covered.

Cleanly-Authored Code - Written in the Angular Way, well-structured with testability in mind.

No Cookie Fallback - With Web Storage being readily available in all the browsers AngularJS officially supports, such fallback is largely redundant.

A sample example is shown below

Working Demo

var eS = angular.module('exampleStore', ['localStorage']);
like image 100
Nidhish Krishnan Avatar answered Nov 05 '22 12:11

Nidhish Krishnan


$rootScope will always reset when the page refreshes, since it's a single-page app.

You need to use something that persists client-side, such as a cookie or sessionStorage (as they both have an expiration time). Take a look at the documentation for $cookieStore: https://docs.angularjs.org/api/ngCookies/service/$cookieStore

Remember, sensitive session information should be encrypted.

like image 25
Andrew Church Avatar answered Nov 05 '22 12:11

Andrew Church


You need to create an api on your server to collect current user. This api must return the same user object as the one you have after you logged in.

For every $route.path you want to secure inside $routeProvider, call this api in the controller using ng-init. If the api returns an object, add the object to your $rootScope, otherwise, force user to the login page.

like image 33
Bram E Pramono Avatar answered Nov 05 '22 11:11

Bram E Pramono