I have a login via Token made with Angular. Once I log in (with the correct data) I navigate to another window like this:
this.router.navigateByUrl('grupo');
And I also keep the access_token and the expire_in in the localStorage . But if instead of logging in I just change the path in the url I can also login.
I need to add this security, that until you log in you cannot navigate to another tab in any case. But how would this be done?
This is the post method I have:
this.http.post(this.url,this.login,opciones)
.subscribe(
data => {
if(data){
this.TOKEN = data["access_token"];
this.EXPIRES = data["expires_in"];
localStorage.setItem('TOKEN',this.TOKEN);
localStorage.setItem('EXPIRE_IN', this.EXPIRES);
this.router.navigateByUrl('grupo');
}
},
error => alert("Fallo de sesion")
)
And these are the options for the POST:
const opciones = {
headers: new HttpHeaders({
'Content-Type':'application/x-www-form-urlencoded',
'Authorization': '--lo que sea--'
}),
params: parametros
};
You have to implement a
guard
to decide if that route can be navigated to or not. Since you want to validate that the user is logged in before navigating to that route, you can create a guard for it.When you implement a
guard
in angular you have to implement the interfaceCanActivate
. Then you define the guard on the route you want it to haveguard
and access to that route be controlled by it.Here is an example of how you could implement it.
authentication.guard.ts
You can generate it with the following angular CLI commandIn your
app.module.ts
or another module you have you define the guard.Documentation about CanActivate .