shadowsora shadowsora - 4 months ago 43
AngularJS Question

Angular $resource factory wont add Auth token header

I have an angular factory called currentUser to hold the user information when they log in to my app (including the auth token). This factory is injected into lots of controllers and in these cases I have no issues when using currentUser.getProfile().token.

I also have various other factories that each return a $resource object for making API calls. In these factories I inject currentUser so that I can get the auth token to add to the request headers. Here is a simplified example of one of these factories:

angular
.module("common.services")
.factory("userAccount",
["$resource",
"appSettings",
"currentUser",
userAccount])

function userAccount($resource, appSettings, currentUser) {
return {
logout: $resource(appSettings.serverPath + "/api/Account/Logout", null,
{
'logoutUser': {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token
}
}
})
}
}


However, currentUser.getProfile().token is always empty and I get an unathorised error, even though when I log the value in one my controllers it is not empty. What could be causing this?

Edit: The issue seems to not just be with the currentUser factory, as when I replace currentUser.getProfile().token with localStorage.getItem('Token') I seem to have the same problem. A controller will correctly log the locally stored token but it will not be added to the headers of API requests.

Answer

You need logout to be a function that returns $resource.

The way you have it now the call to currentUser.getProfile() is being made as soon as the service is initialized which is probably before user even logs in

function userAccount($resource, appSettings, currentUser) {
  return {
    logout: function() {
      return $resource(appSettings.serverPath + "/api/Account/Logout", null, {
        'logoutUser': {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + currentUser.getProfile().token
          }
        }
      })
    }
  }
}

Now the call to get the token won't be made until you call userAccount.logout()