примерно так в методе ран модуля
function run($rootScope, auth) {
// ...
var noAuth = ['page.login','page.404'];
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var isAuth = auth.isAuth();
if (toState.name === 'page.login' && isAuth) {
event.preventDefault();
$rootScope.$state.go('app.home');
}
else if (!(toState.name in noAuth) && !isAuth) {
event.preventDefault();
$rootScope.$state.go('page.login');
}
});
};
храню jwt в локальном хранилище, у него есть expired, то есть можно проверять в геттере, если пользователь подменил вручную, то сервер отдаст 401
function sessionservice($localStorage) {
var service = {
setAccessToken: setAccessToken,
clearAccessToken: clearAccessToken,
getAccessToken: getAccessToken,
getTokenInfo: getAccessTokenOpenInfo
};
return service;
function setAccessToken(tokenData) {
$localStorage.auth = tokenData;
if ($localStorage.auth.expires_in)
$localStorage.auth.expires_in = $localStorage.auth.expires_in * 10e3 + Date.now();
}
function clearAccessToken() {
delete $localStorage.auth;
}
function getAccessToken() {
if (!$localStorage.auth || !$localStorage.auth.expires_in || $localStorage.auth.expires_in < Date.now()) {
clearAccessToken();
return undefined;
}
else
return $localStorage.auth.access_token;
}
function getAccessTokenOpenInfo() {
var token = getAccessToken();
return !token ? undefined : JSON.parse(atob(token.split('.')[1]));
}
}
function authinterceptor($q, $rootScope, session) {
var request = function (config) {
config.headers = config.headers || {};
var token = session.getAccessToken();
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config || $q.when(config);
};
var responseError = function (rejection) {
if (rejection.status === 401) {
session.clearAccessToken();
$rootScope.$state.go('page.login');
}
return $q.reject(rejection);
};
return {
request: request,
responseError: responseError
};
}