I'm comming from angular 1 and i used JWT token to authenticate users. In angular 1 i haved this:
.config(function Config($httpProvider, jwtOptionsProvider) {
// Interceptor for token push on every $http request
jwtOptionsProvider.config({
tokenGetter: ['storageService', function (storageService) {
return storageService.getToken();
}],
whiteListedDomains: ['127.0.0.1', 'localhost'],
unauthenticatedRedirector: ['$state', 'authManager', 'storageService', 'jwtHelper', function ($state, authManager, storageService, jwtHelper) {
if (storageService.getToken() != null) {
if (jwtHelper.isTokenExpired(storageService.getToken())) {
alert('Su sesión ha caducado.');
}
}
storageService.removeToken();
storageService.clearAll();
authManager.unauthenticate();
$state.go('autorepuestos_fe');
}],
unauthenticatedRedirectPath: '/login'
});
$httpProvider.interceptors.push('jwtInterceptor');
})
This are the interceptors. I learn with the official page of JWT for Angular 2 that i can easy intercept the routes of the user and redirect it with AuthGuard. This is ok, i used and works perfectly. But, my question is... on this version of Angular 2 JWT have the unauthenticatedRedirector? With this, if the user makes a request to any endpoint of my backend then automatically shows an message and redirect it to the login page.
Any idea of how i can implement this? I was thinking on put a function that intercept every call to any endpoint and first validate if the token is valid and if this is true then make the request... but sounds complicated.
redirect to login in Angular 2 & 4 can be done by "canActivate" in routing, you can add some message if you want
here is my routing setting for AuthGuard
{ path: 'secret', component: SecretComponent, canActivate: [ AuthService] }
And then in my AuthGuard
public canActivate() {
if (this.checkLogin()) {
return true;
} else {
this.router.navigate(['login']);
return false;
}
}
To show you full details for ASP.NET Angular JWT solution: