How to protect routes at angle 8?

Asked

Viewed 411 times

-1

I am migrating an application from Angular 8 and a great difficulty that I am having is in the routing system, in my application and mandatory this logged in for all routes except for login and registration routes, in Angularjs I used to make this rule in the app.run() I checked if the user was logged in and allowed or denied redirecting to the route, the low code has a simple example of how this was done

    var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
  $routeProvider
  .when("/", {
    templateUrl : "main.htm"
  })
  .when("/red", {
    templateUrl : "red.htm"
  })
  .when("/green", {
    templateUrl : "green.htm"
  })
  .when("/blue", {
    templateUrl : "blue.htm"
  });
});

app.run(function(authService) {
   //aqui eu fazia a regra que se ele nao estivesse logado eu jogava ele pra rota de login
});

at Angular 8 I am not able to restrict the user in the right way by the frontend only by the backend, and I wanted to do this by the front, because my served does not take many requests, then for me it is impractical every time the user accesses a route I go there in the backend check if it is logged and send the confinement, I already have the token and the user data stored in a global variable within a service, however I am only able to restrict the user after he already accessed the route and started the controller so I check if he has the token in the global variable and if I don’t have it I play it to another route, and I wanted it to be done already in the module that provides the routes as I did in the Angularjs, this is possible?

  • search for things canActivate and [Authguard]

1 answer

1


The correct way to restrict routes is to implement the interface CanActivate, which should be used in a routeguard. The tutorial I used to implement this behavior was this.

app/can-Activate-route.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable()
export class CanActivateRouteGuard implements CanActivate {
    constructor(public router: Router) { }

    canActivate(): boolean {
        //implementar este método
    }
}

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { CanActivateRouteGuard } from './can-activate-route.guard';

@NgModule({
  declarations: [
    AppComponent,
    //componentes
  ],
  imports: [
    BrowserModule,
    // declaração de modulos
  ],
  providers: [
    CanActivateRouteGuard //importar como provider este route guard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

src/app/app-routing.modulets.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PublicComponent } from './public/public.component';
import { RestrictComponent } from './restric/restrict.component';
import { CanActivateRouteGuard } from './can-activate-route.guard';


const routes: Routes = [
  { path : 'public', component: PublicComponent},
  { path : 'restrict', component: RestrictComponent, canActivate: [CanActivateRouteGuard]},
  { path : '', redirectTo: '/public', pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The tutorial I followed is in an older version, but I was able to implement with the current version of angular. (9.1).

There is an official angler tutorial, more information here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.