I am looking for a way to do these two things, first I want to redirect the user to a login page if no SessionID is found and second I would like to hear your opinion about persisting session ID in memory only (no cookies).
The solution I came up with for the redirect is:
1 - Create a service called OAuth that will check if SessionID exists and if not, redirects to login page, the service is also responsible for the login and logout methods.
app.factory('OAuth', ['$http', function ($http) {
var _SessionID = '';
return {
login: function () {
//Do login ans store sessionID in var _SessionID
},
logout: function () {
//Do logout
},
isLoggedIn: function () {
if(_SessionID) {
return true;
}
//redirect to login page if false
}
};
}]);
2 - Inject the new OAuth service in each controller and check if user isLoggedIn
app.controller('myCtrl', ['$scope', 'OAuth', function ($scope, OAuth) {
//check if user is logged
OAuth.isLoggedIn();
}]);
Questions:
1 - The isLoggedIn() method will be called in all controllers, so I wonder if there is a way to do this without having to inject the service and call it in each controller.
2 - Instead of having a cookie to store the sessionID I want to save it in OAuth's _SessionID variable and for each request send it to the server. Is this a viable/secure approach? Can you give me some ideas for that?
Thanks!
I use a similar strategy (intercepting 401 responses from the server). You can check out the full example here : https://github.com/Khelldar/Angular-Express-Train-Seed
It uses node and mobgodb on the backend for session store and a trimmed down http interceptor on the client that doens't retry requests like the one Dan linked above:
var interceptor = ['$q', '$location', '$rootScope', function ($q, $location, $rootScope) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 401) {
$location.path('/login');
}
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
I would start here, Witold has created this cool interceptor that works off of http responses. I use it and its been really helpful.
In my case, I used
The code snippet is like this.
noteApp = angular.module('noteApp', ['ngRoute', 'ngCookies'])
.factory('authInterceptor', ['$rootScope', '$q', '$cookies', '$window',
function($rootScope, $q, $cookies, $window) {
return {
request: function (req) {
req.headers = req.headers || {};
if ($cookies.token) {
req.headers.Authorization = 'Bearer ' + $cookies.token;
}
return req;
},
responseError: function (rejection) {
if (rejection.status == 401) {
$window.location = '/auth';
}
return $q.reject(rejection);
}
}
}])
.config(['$routeProvider', '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With