title: AngularJS retrieving user object from controller on every request
body: <p>I have successfully setup a Spring Security project which authenticates the user whenever he logs in. However, after he logs in, I want to retrieve this user object (which is inside the session of Spring security) via the Rest controller in every controller function of AngularJS.</p>
  
  <p>To clarify, how can I call the following method each in every controller to retrieve the user object?</p>
  
  <pre><code>@RequestMapping(value = "/getLoggedInUser", method = RequestMethod.GET, headers = "Accept=application/json")
      public User getLoggedInUser() {
          Authentication auth = SecurityContextHolder.getContext().getAuthentication();
          if (!(auth instanceof AnonymousAuthenticationToken)) {
              User user = (User) SecurityContextHolder.getContext().getAuthentication()
                      .getPrincipal();
              return user;
          }
          return null;
  }
  </code></pre>
  
  <p>What I did was the following:</p>
  
  <pre><code>$http.get(urlBase+'/getLoggedInUser').
   success(function(data) {
       $scope.users = data;
       console.log("The logged in user is: " + data.firstname);
  })
  </code></pre>
  
  <p>This works and it prints the firstname, but I get some odd behaviour when I put the above method inside another $http get method. Is there a better option or possiblity of adding this function at the beginning of every angularjs controller to retrieve this user object and check whether it is null or set (so I can do some logic with it)?</p>
  
  <p>***********UPDATE***********
  After the suggestion of pankajparkar, I was able to now simply retrieve the user object. I put the get method in the application factory directly as such:</p>
  
  <pre><code>myApp.factory('accountService', function($http) {
      return {
           getUser: function() {
               return $http.get(urlBase+'/getLoggedInUser');
           }
       };
  });
  </code></pre>
  
  <p>And from every controller, I can pas the accountService method and do the following:</p>
  
  <pre><code>var handleSuccess = function(user, status) {
       $scope.user = user;
  };
  accountService.getUser().success(handleSuccess);
  </code></pre>
  
  <p>This now works fine and I can get the data in each controller like that. Is this ok? Or can it get a bit nicer than that?</p>