I'm creating an authentication system in angular2 with the idea that if a user that is not authenticated tries to navigated to a "protected" url, the system will redirect the user to the login page putting in the url a query param called "next" that will help the login system redirect the user back to where he wanted to be in the first place.
login?next=my-redirect-url
To protect my components, I'm using the decorator @CanActivate(isUserAuthenticated)
in all of them. The isUserAuthenticated
function is something as follows:
function isUserAuthenticated(
prevInstr: ComponentInstruction,
nextInstr: ComponentInstruction
): boolean {
const authService = injector.get(AuthService);
const router = injector.get(Router);
if(authService.isLoggedIn()) {
return true;
} else {
router.navigate(["/Login", {next: nextInstr.urlPath}]);
return false;
}
}
This approach is not working because the urlPath
property of the nextInstr
is not showing the "complete" url (it lacks query params for example).
Is there a way to build the complete url from a ComponentInstruction
instance like nextInstr
?
Another way (WITHOUT using query parameters using @angular/router 3.0.0) to achieve the same requirement of redirecting to the original requested resource after authentication is to use
RouterStateSnapshot.url
, which is a string that contains the url of the resource the user requested. Before redirecting user back to your login form after a failed authentication attempt, inside of theCanActivate
hook, get the requested url fromRouterStateSnapshot.url
and store it in a variable that is accessible to your login function. When the user logs in successfully simply redirect to the stored URL. Here's my example:My AuthService (below), which performs the login, will redirect user to the originally requested resource on successful login.
This is how your application can remember the originally requested resource WITHOUT using query parameters.
For more details please see the example guide at angular.io starting at the "GUARD THE ADMIN FEATURE" section: https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
Hope this helps someone.
Yes there is a way:
Lets say following structure example depending on routeconfig:
And then you use navigateByUrl to navigate to following url
I have tested it with my example and result you can see on image: