When working with Angular, it's important to understand that all .service and .factory types are singletons. This means that any data or logic you add to a .service or .factory will be accessible throughout the system. For authentication purposes, it is recommended to create an AuthService similar to the following example:
angular.module('my.app.services', []).factory('AuthService', ['$http', function($http) {
var authenticated = false;
var authUrl = '/path/to/auth/handler';
return {
isAuthenticated: function(){
return authenticated;
},
login: function(data) {
return $http.post(authUrl, data).then(function(response) {
authenticated = true;
return authenticated;
}).catch(function(err) {
authenticated = false;
return authenticated;
});
}
};
}]);
By injecting AuthService into any part of your application, you can easily check authentication status using `AuthService.isAuthenticated()`.
In addition, implementing a session cookie is crucial for securing all requests made to the application. Any unauthenticated request should result in an HTTP 403 status code from the server. To handle this globally, setting up an HTTP interceptor is recommended:
angular.module('yourAppName').config(function ($provide, $httpProvider) {
$provide.factory('MyHttpErrorInterceptor', ['$window', '$q', function ($window, $q) {
function notifyError(rejection) {
console.log(rejection);
var errorMessage = '';
switch(rejection.status) {
case 403:
$window.location = 'some/path/to/auth/resource';
break;
case 500:
// Handle server-side exceptions
break;
case 400:
// Handle bad request parameters
break;
default:
errorMessage += 'Request to ' + rejection.config.url + ' failed.';
}
if(rejection.status !== 403) {
// Show error message
}
}
return {
requestError: function (rejection) {
notifyError(rejection);
return $q.reject(rejection);
},
responseError: function (rejection) {
notifyError(rejection);
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('MyHttpErrorInterceptor');
});
The interceptor can also be used to transform requests and responses globally, providing a centralized place for processing HTTP actions in the system. By utilizing interceptors effectively, you can streamline error handling and ensure secure communication within your Angular application.
I hope this guidance helps you get started on the right track!