Answer the question
In order to leave comments, you need to log in
How to check authorization at startup in Angular?
Good afternoon.
Tell me how to properly implement user authentication checks at application startup? I use jwt on the backend to create a token. When I log in, I get a token and store it and data about the user in session storage, but when I close and open the browser, I need to check the authenticity of the token on the back end. I want to do this in the run block, but how can I do it so that I don't get the opportunity to work with the application until the authentication is checked? Suddenly, the user starts not from the first page, but from the "closed" one. Need something like resolve in state
Answer the question
In order to leave comments, you need to log in
something like this in the module's run method
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');
}
});
};
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
};
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question