I’m working on an authentication system and need help with two main tasks:
Send user credentials from login form to authService.fetchToken() which calls apiService.requestToken to get and store the authentication token.
Have authService.fetchToken return the cached token on future calls from different controllers without making new server requests.
Is this approach correct for handling authentication in AngularJS with Web API 2?
My apiService.requestToken method works fine when I provide credentials and returns a valid token. However, I’m unsure about the best way to cache this token for later use in other controllers that require authentication. Any guidance would be appreciated.
securityApp.factory("authService", function (apiService) {
function fetchToken(userEmail, userPass) {
var authToken;
if (!!authToken) {
apiService.requestToken(userEmail, userPass).then(function (response) {
authToken = response;
});
};
return authToken;
}
});
securityApp.factory("apiService", function ($http, $q) {
function requestToken(userEmail, userPass) {
return $http({
method: 'POST', url: '/authenticate', data: { email: userEmail, pass: userPass, grant_type: 'password' }, transformRequest: function (data) {
var params = [];
for (var key in data)
params.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
return params.join("&");
}
})
.then(function (response) {
return response.data.access_token;
}, function (error) {
return $q.reject(error.data);
});
}
return {
requestToken: requestToken
};
});
Auth flows like this are perfect for automation. I’ve built similar systems - manual token management becomes a nightmare at scale.
Your main issue is mixing sync and async operations. fetchToken returns undefined because you’re not waiting for the promise to resolve.
But why handle this complexity manually? I automated our entire auth flow - token refresh, storage, retry logic. No more localStorage headaches, expiration handling, or promise chains.
Set up an automated workflow that:
Captures login attempts
Manages token lifecycle automatically
Handles refresh tokens before expiration
Retries failed requests with new tokens
Logs auth events for monitoring
This removes all the boilerplate and state management headaches. Your controllers just make requests - everything else happens behind the scenes.
I’ve seen teams spend weeks debugging auth edge cases that automation solves in minutes. Token rotation, concurrent requests, logout cleanup - it all runs automatically.
I hit this exact same timing issue when I was building JWT auth last year. The real problem isn’t your boolean check - you’re treating async operations like they’re synchronous. Your fetchToken function returns authToken right away, but the HTTP request hasn’t finished yet, so authToken is still undefined. Here’s how I fixed it: restructure your service to keep token state at the module level and always work with promises. Store the token as a service property instead of a local variable. When fetchToken gets called, check if you’ve got a valid token and return it wrapped in a resolved promise. No token? Make the API call and cache it. This way your controllers always expect a promise whether it’s fresh or cached. Also throw in some token expiration logic since Web API 2 tokens usually come with expiry info.
hey, you’re close but your fetchToken logic is backwards. you’re checking !!authToken which starts as undefined, so the api call never happens. change it to if (!authToken) instead. and don’t forget to return the promise properly!
localStorage works perfectly for this. I’ve used it for token storage for years - just call localStorage.setItem('authToken', token) after the API response and localStorage.getItem('authToken') to grab it later. Way easier than dealing with complex state management and it survives page reloads.
Your token keeps getting reset because it’s a local variable that dies after each service call. You need proper state management. I hit the same problem building auth for our SPA. Your authService needs to keep state between different controller instances. Try using a closure or module-level variable to store the token. You’re also missing something important: handle cases where credentials aren’t provided on later calls. Make fetchToken accept optional parameters and return the cached token when no credentials come in. Don’t forget token validation before returning cached values. Tokens expire or get revoked server-side, so you need to catch these cases and handle them gracefully.