javascriptangularjs

Angular app should stay logged in, until app is open in browser


I have one Angular app with authentication, everything is working good as expected.

But we need that application/session/token should be valid even though there is not activity and app is still open in browser.

and token should be expired only if user do logout himself.

I have an idea, but don't know how should I implement it at application level.

I want to sent one request to API that will refresh the accesstoken every 10 mins.

Where can I implement this logic?


Solution

  • Well on the front end you can keep the token saved in a cookie or $window.sessionStorage and you can keep using it for the further API calls which need authentication. You can create a factory to save token

     .factory('Authentication', function ($window){
    
        return {
    
         store_token: function(token){
            $window.sessionStorage.setItem('token', token);
         },
    
    
         get_token: function(){
           return $window.sessionStorage.getItem("token");
         }
      };
     });
    

    Then in controller

      .controller( 'MyCtrl', function ( $scope, Athentication, Api, $interval){
    
      function myfunction()
         Api.get_token({username: $scope.username, password: $scope.password}).$promise.then(function(data){
           if(data.success){
             Authentication.store_token(data.token);
    
           }
         });
      myfunction(); 
      $interval(myfunction, 1000 * 60 * 10); 
     });