Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Prevent authenticated users from accessing specific routes

I've defined some routes in my main.ts file:

const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '', redirectTo: 'home', terminal: true },
  { path: 'dashboard', component: DashboardComponent, canActivate: [LoggedInGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent } 
];

After successful login I want my authenticated users can be able to use specific routes (e.g. dashboard). And without login they cannot access dashboard but they can be able to visit about,home,login

I've managed to restrict users traversing the dashboard without login, using CanActivate.

canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true; 
    }
    this.router.navigateByUrl('/login');
    return false;
  }

But Using those routes and the CanActivate approach after successful login, users are also able to goto routes like login, home. How can I prevent that?

N.B. I'm using angular2 RC4.

like image 482
Emu Avatar asked Aug 12 '16 10:08

Emu


People also ask

Which of the below method is used to prevent unauthenticated users from accessing restricted routes?

That is called AuthGuard. AuthGuard is used to protect the routes from unauthorized access.

Which route Guard is helpful in preventing an authenticated access to a component?

Introduction. The Angular router's navigation guards allow to grant or remove access to certain parts of the navigation. Another route guard, the CanDeactivate guard, even allows you to prevent a user from accidentally leaving a component with unsaved changes.

Which route Guard can be used to check if a user can visit a route?

CanActivate. Checks to see if a user can visit a route. CanActivateChild. Checks to see if a user can visit a routes children.

Which method of RouterModule should be called for providing all routes in AppModule?

Which method of RouterModule provides all routes in AppModule? Ans. RouterModule. forRoot is used for providing all routes in AppModule.


2 Answers

I made some researches to see if it's possible to "negate" a guard but seems like you have to make another guard which is the opposite of your guard. Like :

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './your-auth.service';

@Injectable()
export class PreventLoggedInAccess implements CanActivate {

  constructor(private authService: AuthService) {}

  canActivate() {
    return !this.authService.isLoggedIn();
  }
} 

Add it in your bootstrap function as well and you are all set. You just have to do in your routes :

{ path: 'login', component: LoginComponent, canActivate: [PreventLoggedInAccess] },
like image 165
Adam S Avatar answered Oct 20 '22 06:10

Adam S


Make ts file name auth.guard.ts put following code on that

Write guard code

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

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router) { }
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

Add bellow code in your routing ts file

app-routing.module.ts

{
      path: 'user', component: UserComponent,canActivate: [AuthGuard] ,
      children: [{ path: 'home', component: HomeComponent },
                 { path: 'view/:id', component: UserViewComponent },
                 { path: 'add', component: UserAddComponent },
                 { path: 'edit/:id', component: UserAddComponent }
                ]  
  },

Add providers in your app.module.ts file

app.module.ts

@NgModule({
  declarations: [
    AppComponent
    --------
  ],
  imports: [
    BrowserModule
    --------
  ],
  providers: [      
    AuthGuard        
  ],
  bootstrap: [AppComponent]
})
like image 24
Pavan Hukerikar Avatar answered Oct 20 '22 04:10

Pavan Hukerikar