AngularJS - store basic authentication on login

后端 未结 5 1840
忘掉有多难
忘掉有多难 2021-01-18 07:35

I\'m banging my head on a wall with this - I\'m relatively new to working with APIs and have yet to do anything that requires authentication.

I\'m stuck with sendin

5条回答
  •  难免孤独
    2021-01-18 08:04

    In such cases what I usually have been doing is store any login token or such credentials(not passwords) in cookies and then access it via an angular service. Since angular services are singletons the value is retained throughout the app unless the page reloads which is where the cookie comes into play. An example service that might look something like this

    (function(){
      function Factory($resource, $q, $window, User, $cookie){
        var Resource = $resource(
                        // your resource config
                      ),
        res = Resource,
        proto = res.prototype;
    
        res.currentToken = null;
        res.currentUser = null;
    
    
        res.unsetAuthProperties = function() {
          delete $cookie.authToken;
          res.currentToken = null;
          res.currentUser = null;
        };
    
        // call this method after you retrieve the credentials
        res.setAuthProperties = function(response) {
          if(!response.id) {  
            res.unsetAuthProperties();
          } else {
            res.currentToken = {
              id: response.id,
              value: response.value
            };
          // set the current user
          res.currentUser = User.getInstance(response.jw_tokenable);
          // set the token in the cookie
          $cookie.authToken = res.currentToken.value;
        }
      };
    
      res.resolveCurrentUser = function () {
        var defered = $q.defer();
        // if the user is already signed in 
        // resolve the promise
        // if not do a manual resolve
        res.isSignedIn() ? defered.resolve() : resolve();
        // get the current user from the server
        // and resolve the promise
        function resolve () {
          res.current().$promise
          .then(function(response) { 
            res.setAuthProperties(response); 
          })
          .finally(function() { 
            res.isSignedIn() ? defered.resolve() : defered.reject(); 
          });
        };
    
        return defered.promise;
      };
    
      return res;
    
    };
    

    Once you have such a service ready use an angular interceptor to intercept the requests to which you want to add the auth headers to. https://docs.angularjs.org/api/ng/service/$http

提交回复
热议问题